Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Emit an event when a specific piece of state changes in vuex store

Tags:

vue.js

vuex

I have a Vuex store with the following state:

state: {
    authed: false,
    id: false
}

Inside a component I want to watch for changes to the authed state and send an AJAX call to the server. It needs to be done in various components.

I tried using store.watch(), but that fires when either id or authed changes. I also noticed, it's different from vm.$watch in that you can't specify a property. When i tried to do this:

store.watch('authed', function(newValue, oldValue){
  //some code
});

I got this error:

[vuex] store.watch only accepts a function.

Any help is appreciated!

like image 205
ierdna Avatar asked Oct 03 '16 15:10

ierdna


2 Answers

Just set a getter for the authed state in your component and watch that local getter:

watch: {
  'authed': function () {
    ...
  }
}
like image 75
Primoz Rome Avatar answered Oct 11 '22 16:10

Primoz Rome


Or you can use ...

let suscribe = store.subscribe((mutation, state) => {
  console.log(mutation.type)
  console.log(mutation.payload)
})
// call suscribe() for unsuscribe

https://vuex.vuejs.org/api/#subscribe

like image 38
Emiliano Díaz Avatar answered Oct 11 '22 17:10

Emiliano Díaz