如果我有商店:
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
export default new Vuex.Store({
state: {
foo: bar
},
mutations: {
updateComponent (state) {
// computation and logic
// update state
this.$refs.myComponent.updateComponent(state.foo)
}
}
}
我有一个组件,其引用为'myComponent':
<template>
...
</template>
<script>
export default {
...
methods: {
updateComponent(payload) {
// do stuff
}
}
}
</script>
我想从商店中调用“ updateComponent()”方法。我可以从其他视图和组件中使用this.$refs.myComponent
,但是在商店中无法使用。我收到错误TypeError: Cannot read property 'myComponent' of undefined
。
从商店使用this
显然不是this.$refs.myComponent
的正确范围。
我可以通过商店突变致电updateComponent()
吗?
答案 0 :(得分:0)
您可以使用vuex
的订阅方法。在安装阶段订阅您的组件:
mounted() {
this.$store.subscribe((mutation, state) => {
switch(mutation.type) {
case 'updateComponent':
// Update your component with new state data
break;
}
})
}