Skip to content
Advertisement

How can I get ReactJS prevProps and prevState equivalent in Vue

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

componentDidUpdate(prevProps, prevState){
  if(prevState.update !== this.state.update){
   // Fetch data...
  }
}

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:

new Vue({
    el: '#app',
  data() {
    return {
        message: 'initial message'
    }
  },
  watch:{
    message(newVal, oldVal){
        if(oldVal != newVal) {
        console.log('message updated.');
        console.log('oldVal:', oldVal);
        console.log('newVal:', newVal);
      }
    }
  },
  mounted() {
    setTimeout(()=>{
        this.message = 'updated message'
    }, 3000);
  }
});

Here is the jsfiddle

You can read more about watch api

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement