如何在 vuex 中同步观察状态变化? [英] How can I watch synchronously a state change in vuex?

查看:39
本文介绍了如何在 vuex 中同步观察状态变化?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用开源 vuejs + vuex 项目,这是源 https://github.com/misterGF/CoPilot/tree/master/src/components

I am using an opensource vuejs + vuex project and this is the source https://github.com/misterGF/CoPilot/tree/master/src/components

我目前在知道如何触发从一个组件到另一个组件的事件时遇到问题.

I am currently having problems knowing how to trigger an event from one components to another.

我可以使用 this.$state.store.commit("foo", "bar") 来存储 vuex 中的信息,但是当两个单独有两个不同时 export default {} 我不知道如何让应用程序知道每当foo"例如更改为baz"时……除非我刷新/重新加载应用程序,否则我无法知道更改

I can use this.$state.store.commit("foo", "bar") to store information in vuex, but when two seperate have two difference export default {} I don't know how I can make the app aware whenever "foo" is for exampled changed to "baz" ... unless I refresh/reload the app, there is no way for me to know the changes

推荐答案

在你的组件上使用 this.$store.watch.Created() 是放置它的好地方.您将状态传递给它,然后指定它更改时的回调.Vuex 文档没有给出很好的例子.查找有关 此 Vuejs 论坛的更多信息页.Store watch 的功能与 vm.$watch 相同,因此您可以在 这里阅读更多关于Vue 文档.

Use this.$store.watch on your component. Created() is a good place to put it. You pass it the state to watch and then specify the callback for when it changes. The Vuex docs do not give good examples. Find more information on this Vuejs Forum page. Store watch functions the same as the vm.$watch, so you can read more about that 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
    }
  )

这篇关于如何在 vuex 中同步观察状态变化?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆