我同时使用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组件?


当前回答

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

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

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

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

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

其他回答

其实很简单:

watch: {
  '$store.state.drawer': function() {
    console.log(this.$store.state.drawer)
  }
}

如果存储在一个模块中,使用:

'$store.state.myModule.drawer'

对于嵌套文件,使用:

'$store.state.fileOne.fileTwo.myModule.drawer'

你不应该使用组件的监视器来监听状态的变化。我建议您使用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

如上所述,直接在商店中观察变化并不是一个好主意

但在一些非常罕见的情况下,它可能对某人有用,所以我将留下这个答案。其他情况请参见@gabriel-robert answer

你可以通过州政府,$watch。将此添加到组件中创建的(或需要执行此方法的地方)方法中

this.$store.watch(
    function (state) {
        return state.my_state;
    },
    function () {
        //do something on data change
    },
    {
        deep: true //add this if u need to watch object properties change etc.
    }
);

详情:https://vuex.vuejs.org/api/#watch

Vue手表处于字符串状态

状态:

$store.state.local_store.list_of_data

内部组件

  watch: {
       
       '$store.state.local_store.list_of_data':{//<----------your state call in string
        handler(){
            console.log("value changeing in party sales entry"); //<---do your stuff here
        },
        deep:true
       }

    },

你也可以使用debouncedWatch (vue使用函数)安全地观看它

  debouncedWatch(
    lines,
    () => {
      console.log('changed');
    },
    500,
  );