I'm trying to append a click event to an already existing dom element.
<div class="logMe" data-log-id="{{ data.log }}"></div>
...
<div id="events"></div>
I can't seem to access outside vue methods within my jquery click handler. It will throw logData is not defined.
new Vue({
el: '#events',
mounted() {
$('.logMe').on('click', function() {
const data = $(this).data('log-id');
this.logData(data); // throws logData is not defined
});
},
methods: {
logData(id) {
console.log(id); // never fires
... hit server
},
},
});
If anyone knows of a better way to append click events to .html elements that would be great! But how can I bubble up and find my vue methods? Here's a fiddle to illustrate
To get your code working you would write it like this:
console.clear()
new Vue({
el: '#events',
mounted() {
$('.logMe').on('click', (evt) => {
console.log("called")
const data = $(evt.target).data('logId');
this.logData(data);
});
},
methods: {
logData(id) {
console.log(id);
},
},
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://unpkg.com/vue#2.4.2"></script>
<div class="logMe" data-log-id="10">Something</div>
<div id="events"></div>
Note that the code uses an arrow function to define the click handler so that the appropriate this is captured to call the logData method on the Vue. However, doing that means you lose the this you want to get the data from the data property, so instead the example uses evt.target.
There is an alternative approach where you capture the Vue in a variable and call the method directly from your jQuery event.
console.clear()
const app = new Vue({
el: '#events',
methods: {
logData(id) {
console.log(id); // never fires
},
},
});
$('.logMe').on('click', function(){
app.logData($(this).data("logId"))
});
<script src="https://unpkg.com/vue#2.4.2"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<div class="logMe" data-log-id="10">Something</div>
<div id="events"></div>
Much easier solution =
window.app = new Vue({
el: "#app",
methods: {
myMethod(data) { ... }
}
}
// jQuery
window.app.myMethod(data);
Related
Just started learning Vue yesterday and I love it. I'm trying to trigger an event when a user clicks on an anchor with a phone number:
var phoneNumbers = new Vue({
el: "a[href^='tel:']",
methods: {
onClick() { console.log('a phone number was clicked'); }
}
})
The issue is, I would like to (in this particular case), not have to add v-on:click="" to the actual element. This is because I'm dealing with a CMS where users may add links to phone numbers where they wouldn't be adding the vue attributes to the markup.
Any way of accomplishing this?
Thanks!
You have a reference to the component's root DOM element via this.$el.
You can add a click listener in the mounted hook (you'll also need to remove the listener in the destroyed hook as well):
mounted() {
this.$el.addEventListener('click', this.onClick);
},
destroyed() {
this.$el.removeEventListener('click', this.onClick);
}
Here's a working example:
Vue.config.productionTip = false;
Vue.config.devtools = false;
var phoneNumbers = new Vue({
el: "a[href^='tel:']",
methods: {
onClick() {
console.log('a phone number was clicked');
}
},
mounted() {
this.$el.addEventListener('click', this.onClick);
},
destroyed() {
this.$el.removeEventListener('click', this.onClick);
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
555-555-5555
I want to change a data property and run a method on my Vue instance within Laravel. However due to using webpack and laravel I can't seem to access the instance how I would expect to:
So window.app doesn't appear to be the correct instance of my Vue class.
Below is the Blade View i'm loading, as you can see I append a script tag to my main layout.blade.php, simply trying to change the Vue instance data property, and run a method.
#push('scripts')
<script>
app.unsaved = true;
app.triggerEvent(null, 'models', null);
</script>
#endpush
Below is part of my app.js (resources/assets/js/app.js):
const app = new Vue({
el: '#app',
components: {
'models-select': ModelsSelect
},
data: {
showModel: false,
unsaved: false
},
mounted: function() {
let _self = this;
(function() {
document.querySelectorAll("input, textarea, select").forEach(function(e) {
e.addEventListener('change', function() {
_self.unsaved = true;
e.classList.add('is-changed');
});
});
function unloadPage(){
if (_self.unsaved) return 'You appear to have un-saved changes!';
}
window.onbeforeunload = unloadPage;
})();
},
methods: {
triggerEvent: function(event, target, property)
{
app.$refs[target].update(event, property);
}
As you can see i'd expect to manipulate the Vue instance through the global app variable I have defined within the app.js. However this doesn't appear to be the case.
I get the following error when running the triggerEvent method:
app.triggerEvent is not a function
In your app.js file, change const app = new Vue({ to window.app = new Vue({.
Then within your <script> tags, change it to this.
<script>
window.app.unsaved = true;
window.app.triggerEvent(null, 'models', null);
</script>
I'm trying to get a simple Vue+Firebase app running that allows you to send strings to the firebase database and have the messages be displayed using the "v-for" directive. However, I keep getting the error
Property or method "messages" is not defined on the instance but referenced during render
even though I'm pretty sure I'm using the correct syntax based on Vue's example on their site and the Vuefire github page to link up messages to the database. I can push to the database just fine, but for some reason I can't read the data from the database. I've been unable to get this to work for about a day and at this point any help is appreciated.
Here is my code for reference:
index.html:
<head>
<script src="https://www.gstatic.com/firebasejs/5.2.0/firebase.js"></script>
<script>
// Initialize Firebase
var config = { ... };
firebase.initializeApp(config);
</script>
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
</head>
<body>
<div id="app">
<input type="text" v-model="message" placeholder="Type a message!">
<button v-on:click="sendData">Send Data</button>
<br>
<h3 v-for="msg in messages">{{msg.value}}</h3>
</div>
<script type="text/javascript" src="app.js"></script>
</body>
app.js:
var messageRef = firebase.database().ref('local/responses');
var app = new Vue({
el: '#app',
data: function () {
return {
message: ''
}
},
firebase: function () {
return {
messages: messageRef
}
},
methods: {
sendData: function () {
messageRef.push(this.message);
this.message = '';
}
}
});
You need to include the messages property in both the firestore return function as a database reference, as well as the data return function as an empty array for the database to bind to, as such.
var app = new Vue({
el: '#app',
data: function () {
return {
message: '',
messages: []
}
},
firebase: function () {
return {
messages: firebase.database().ref('local/responses')
}
},
methods: {
sendData: function () {
messageRef.push(this.message);
this.message = '';
}
}
});
This happens because you're trying to bind the Firestore reference to a piece of data that doesn't exist within your Vue instance, it needs that empty array for it to bind to the data property.
I have component
and i want run method after click
<my-component #click="showOtherDiv"></my-component>
i have this method on main app methods
var app = new Vue({
el: '#app',
data: {},
methods: {
showOtherDiv : function(){
alert('Some message');
}
}
});
but seems like "click" not works on full component
Register your component, and declare the handler method inside:
Vue.component('my-component', {
// ...
methods: {
showOtherDiv : function(){
alert('Some message');
}
}
});
Add the .native modifier to the event name:
<my-component #click.native="showOtherDiv"></my-component>
From the docs:
Binding Native Events to Components
[…] when you want to listen for a native event on the root element of a component […] you can use the .native modifier for v-on.
I am trying to call a parent/root level method on a child component in Vue.js, but I keep getting a message saying TypeError: this.addStatusClass is not a function.
Vue.component('spmodal', {
props: ['addStatusClass'],
created: function() {
this.getEnvironments();
},
methods: {
getEnvironments: function() {
this.addStatusClass('test');
}
}
});
new Vue({
el: '#app',
methods: {
addStatusClass(data) {
console.log(data);
}
}
});
Here is a full JSBIN example: http://jsbin.com/tomorozonu/edit?js,console,output
If I call this.$parent.addStatusClass('test'); it works fine, but based on the Vue.js documentation, this is bad practice and I should be using props which is not working.
specifying the prop does nothing on its own, you have to actually pass something to it from the parent - in this case, the function.
<spmodal :add-status-class="addStatusClass"></spmodal>