I want to make a network request every time a certain value in my state updates. I want the network request function to be called only when that particular value changes. In React I’do something like this
JavaScript
x
6
1
componentDidUpdate(prevProps, prevState){
2
if(prevState.update !== this.state.update){
3
// Fetch data...
4
}
5
}
6
How can I replicate this in Vue, can I do it from the updated()
lifecycle hooks? I can’t seem to catch previous props or state value
Advertisement
Answer
You can use watchers. Also you can take a look at the example below:
JavaScript
1
23
23
1
new Vue({
2
el: '#app',
3
data() {
4
return {
5
message: 'initial message'
6
}
7
},
8
watch:{
9
message(newVal, oldVal){
10
if(oldVal != newVal) {
11
console.log('message updated.');
12
console.log('oldVal:', oldVal);
13
console.log('newVal:', newVal);
14
}
15
}
16
},
17
mounted() {
18
setTimeout(()=>{
19
this.message = 'updated message'
20
}, 3000);
21
}
22
});
23
Here is the jsfiddle
You can read more about watch api