我同时使用vuex和vuejs 2。

我是vuex的新手,我想看一个商店变量的变化。

我想在我的vue组件中添加手表功能

这是我目前所拥有的:

import Vue from 'vue';
import {
  MY_STATE,
} from './../../mutation-types';

export default {
  [MY_STATE](state, token) {
    state.my_state = token;
  },
};

我想知道my_state是否有任何变化

我怎么看店。My_state在我的vuejs组件?


当前回答

在组件内部,创建一个计算函数

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

现在可以观察计算出的函数名,比如

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

在vuex状态my_state中所做的更改将反映在计算函数myState中,并触发手表函数。

如果状态my_state包含嵌套数据,则处理程序选项将提供更多帮助

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

这将监视my_state存储中的所有嵌套值。

其他回答

你不应该使用组件的监视器来监听状态的变化。我建议您使用getter函数,然后在组件中映射它们。

import { mapGetters } from 'vuex'

export default {
  computed: {
    ...mapGetters({
      myState: 'getMyState'
    })
  }
}

在你的店里:

const getters = {
  getMyState: state => state.my_state
}

您应该能够通过使用此功能侦听对您的商店所做的任何更改。myState在你的组件。

https://vuex.vuejs.org/en/getters.html#the-mapgetters-helper

当你想要在状态级别上观看时,可以这样做:

let App = new Vue({
    //...
    store,
    watch: {
        '$store.state.myState': function (newVal) {
            console.log(newVal);
            store.dispatch('handleMyStateChange');
        }
    },
    //...
});

我使用的一个非常简单的计算方法是这样的。也许这对你有帮助。

  const variable_name = computed(
        () => store.state.[name_of_state].property_name
      );

你可以这样做的另一个版本是

computed: {
  name () {
    return this.$store.state.[name_of_state].property
  }
}

这是从存储中访问getter的一种格式。 希望你今天过得愉快。

如果你使用typescript,那么你可以:

import {Watch} from "vue-property-decorator"; .. @Watch (" $ store.state.something”) private watchSomething() { //使用这个。$store.state。可以访问的东西 ... }

在computed中使用你的getter,然后观察它并做你需要做的事情

    computed:{
    ...mapGetters(["yourGetterName"])
 },
 watch: {
    yourGetterName(value) {
       // Do something you need
    },

  }