Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I watch synchronously a state change in vuex?

Tags:

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

like image 909
hidar Avatar asked Sep 07 '17 12:09

hidar


People also ask

Are Vuex actions synchronous?

In Vuex, actions are functions that call mutations. Actions exist because mutations must be synchronous, whereas actions can be asynchronous. You can define actions by passing a POJO as the actions property to the Vuex store constructor as shown below. To "call" an action, you should use the Store#dispatch() function.

How do I watch Vuex store values?

To watch store values from Vuex, we can add a watcher in our component to watch the store value. to watch the $store. state. drawer value in our component by setting '$store.

Is Vuex state reactive?

Vuex stores are reactive. When Vue components retrieve state from it, they will reactively and efficiently update if the store's state changes. You cannot directly mutate the store's state. The only way to change a store's state is by explicitly committing mutations.

How do I use async await in Vuex?

To use async and await with Vuex dispatch, we can add an action method that's an async function. const store = new Vuex. Store({ //... actions: { getProducts: async ({ commit }, type) => { try { const { data: products } = await axios.


1 Answers

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     }   ) 
like image 200
For the Name Avatar answered Oct 14 '22 07:10

For the Name