hidar
hidar

Reputation: 5939

How can I watch synchronously a state change in vuex?

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.

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

Upvotes: 25

Views: 33486

Answers (2)

For the Name
For the Name

Reputation: 2529

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
    }
  )

Upvotes: 43

Stephan-v
Stephan-v

Reputation: 20289

Your question is not entirely clear so I am going to make some assumptions here.

If you simply want your app to know when a store value has changed you can use a watcher to watch a computed property that is directly linked to a store getter:

So you would set a watcher on something like this:

computed: {
  doneTodosCount () {
    return this.$store.getters.doneTodosCount
  }
},
watch:{
    doneTodosCount(value) {
       console.log(`My store value for 'doneTodosCount' changed to ${value}`);
    }
}

If you want your commit to behave differently depending on what the current value of your foo property is set to, then you can simply check for this in your commit function.

Let me know if you have some more questions.

Upvotes: 25

Related Questions