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