I have method that changes data in itself, simple example:
Vue.component('component', {
template: '#component',
data: function () {
return {
dataToBeWatched: ''
}
},
methods: {
change: function (e) {
var that = this;
setTimeOut(function() {
that.dataToBeWatched = 'data changed';
}, 2000);
},
makeSmthWhenDataChanged: function () {
// ajax request when dataToBeWatched changed or when dataToBeWatched isn't empty
}
}
});
How to create such watcher using correct methods vue js? Or I need to use props watching it in component?
Using watchers in Vue # vue file we can watch for changes in data or props by using watch . For example, the below code will watch for a change in the data element pageData , and run a function according to the value it is changed to.
Each Vue component instance goes through a series of initialization steps when it's created - for example, it needs to set up data observation, compile the template, mount the instance to the DOM, and update the DOM when data changes.
The $el option in Vue provides Vue with an existing HTML element to mount the Vue instance generated using the new keyword. this. $el. querySelector is used to access HTML elements and modify the element's properties.
Vue components can have a watch
property which is an object. The object keys need to be the name of the prop or data that needs to be watched, and the value is a function that is invoked when the data changes.
https://vuejs.org/v2/guide/computed.html#Computed-vs-Watched-Property
Vue.component('component', {
template: '#component',
data: function () {
return {
dataToBeWatched: ''
}
},
methods: {
change: function (e) {
var that = this;
setTimeOut(function() {
that.dataToBeWatched = 'data changed';
}, 2000);
},
makeSmthWhenDataChanged: function () {
// ajax request when dataToBeWatched changed or when dataToBeWatched isn't empty
}
},
watch: {
dataToBeWatched: function(val) {
//do something when the data changes.
if (val) {
this.makeSmthWhenDataChanged();
}
}
}
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With