Search code examples
vue.jsvuex

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!


Solution

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

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