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


当前回答

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

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

其他回答

这是为所有的人,不能解决他们的问题与getter,实际上真的需要一个监视器,例如,与非Vue第三方的东西(见Vue监视器何时使用监视器)。

Vue组件的监视器和计算值也都适用于计算值。所以vuex也没有什么不同:

import { mapState } from 'vuex';

export default {
    computed: {
        ...mapState(['somestate']),
        someComputedLocalState() {
            // is triggered whenever the store state changes
            return this.somestate + ' works too';
        }
    },
    watch: {
        somestate(val, oldVal) {
            // is triggered whenever the store state changes
            console.log('do stuff', val, oldVal);
        }
    }
}

如果只是结合本地和全局状态,mapState的文档也提供了一个例子:

computed: {
    ...mapState({
        // to access local state with `this`, a normal function must be used
        countPlusLocalState (state) {
          return state.count + this.localCount
        }
    }
})

您还可以在vue组件中使用mapState来直接从存储中获取状态。

在你的组件中:

computed: mapState([
  'my_state'
])

其中my_state是存储中的变量。

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

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

您可以使用Vuex操作、getter、计算属性和监视器的组合来侦听Vuex状态值的变化。

HTML代码:

<div id="app" :style='style'>
  <input v-model='computedColor' type="text" placeholder='Background Color'>
</div>

JavaScript代码:

'use strict'

Vue.use(Vuex)

const { mapGetters, mapActions, Store } = Vuex

new Vue({
    el: '#app',
  store: new Store({
    state: {
      color: 'red'
    },
    getters: {
      color({color}) {
        return color
      }
    },
    mutations: {
      setColor(state, payload) {
        state.color = payload
      }
    },
    actions: {
      setColor({commit}, payload) {
        commit('setColor', payload)
      }
    }
  }),
  methods: {
    ...mapGetters([
        'color'
    ]),
    ...mapActions([
        'setColor'
    ])
  },
  computed: {
    computedColor: {
        set(value) {
        this.setColor(value)
      },
      get() {
        return this.color()
      }
    },
    style() {
        return `background-color: ${this.computedColor};`
    }
  },
  watch: {
    computedColor() {
        console.log(`Watcher in use @${new Date().getTime()}`)
    }
  }
})

参见JSFiddle演示。

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

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

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

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

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