ierdna
ierdna

Reputation: 6293

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

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!

Upvotes: 20

Views: 32130

Answers (2)

Emiliano Díaz
Emiliano Díaz

Reputation: 694

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

Upvotes: 16

Primoz Rome
Primoz Rome

Reputation: 11031

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

watch: {
  'authed': function () {
    ...
  }
}

Upvotes: 36

Related Questions