Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
77
rated 0 times [  82] [ 5]  / answers: 1 / hits: 42233  / 7 Years ago, wed, december 13, 2017, 12:00:00

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?


More From » methods

 Answers
23

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://v2.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();
}
}
}
});

[#55693] Friday, December 8, 2017, 7 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
daren

Total Points: 577
Total Questions: 114
Total Answers: 120

Location: Malaysia
Member since Fri, Dec 3, 2021
3 Years ago
;