我正在使用一个开源的vuejs + vuex项目,这是源代码https://github.com/misterGF/CoPilot/tree/master/src/components
我目前在知道如何将事件从一个组件触发到另一个组件时遇到了问题。
我可以使用this.$state.store.commit("foo", "bar")
在vuex中存储信息,但是当两个不同的export default {}
有两个不同的vuex时,我不知道如何让应用程序在"foo“被更改为"baz”的时候意识到这一点。除非我刷新/重新加载应用程序,否则我无法知道这些更改
发布于 2017-09-07 14:34:04
在您的组件上使用this.$store.watch。Created()是一个放置它的好地方。您向它传递要监视的状态,然后指定当它发生更改时的回调。Vuex文档没有给出很好的例子。在this Vuejs Forum page上查找更多信息。Store watch的功能与vm.$watch相同,因此您可以阅读有关该here in the Vue docs的更多信息。
this.$store.watch(
(state)=>{
return this.$store.state.VALUE_TO_WATCH // could also put a Getter here
},
(newValue, oldValue)=>{
//something changed do something
console.log(oldValue)
console.log(newValue)
},
//Optional Deep if you need it
{
deep:true
}
)
发布于 2017-09-07 13:21:02
你的问题不完全清楚,所以我将在这里做一些假设。
如果你只是想让你的应用程序知道某个商店的值什么时候改变了,你可以使用一个监视器来监视一个直接链接到一个商店getter的计算属性:
所以你可以在下面这样的东西上设置一个观察者:
computed: {
doneTodosCount () {
return this.$store.getters.doneTodosCount
}
},
watch:{
doneTodosCount(value) {
console.log(`My store value for 'doneTodosCount' changed to ${value}`);
}
}
如果希望根据foo
属性的当前值设置不同的提交行为,那么只需在提交函数中进行检查即可。
如果你有更多的问题,请告诉我。
https://stackoverflow.com/questions/46096261
复制相似问题