vue.js 2 how to watch store values from vuex

后端 未结 18 2226
傲寒
傲寒 2020-11-27 10:26

I am using vuex and vuejs 2 together.

I am new to vuex, I want to watch a store variable change.

I want t

18条回答
  •  一生所求
    2020-11-27 10:47

    Inside the component, create a computed function

    computed:{
      myState:function(){
        return this.$store.state.my_state; // return the state value in `my_state`
      }
    }
    

    Now the computed function name can be watched, like

    watch:{
      myState:function(newVal,oldVal){
        // this function will trigger when ever the value of `my_state` changes
      }
    }
    

    The changes made in the vuex state my_state will reflect in the computed function myState and trigger the watch function.

    If the state my_state is having nested data, then the handler option will help more

    watch:{
      myState:{
        handler:function(newVal,oldVal){
          // this function will trigger when ever the value of `my_state` changes
        },
        deep:true
      }
    }
    

    This will watch all the nested values in the store my_state.

提交回复
热议问题