我同时使用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组件?
这是为所有的人,不能解决他们的问题与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
}
}
})
如上所述,直接在商店中观察变化并不是一个好主意
但在一些非常罕见的情况下,它可能对某人有用,所以我将留下这个答案。其他情况请参见@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
在组件内部,创建一个计算函数
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