Two less known facts about Vuex

Nicolò Maria Mezzopera

Nicolò Maria Mezzopera

Mar 3, 2019
2 min read
Share on Twitter or LinkedIn

When using Vuex in our Vue.js components we tend to forget the amazing API that it exposes beside the mapping functions.

Let's see what we can do with it, but first let's create a basic store for our examples:

const store = new Vuex.Store({
  state: {
    count: 0
  },
  getters: {
    getCountPlusOne: state => state.count + 1
  },
  mutations: {
    increment(state) {
      state.count++;
    }
  }
});

# Watch

The watch method is the most useful to integrate Vuex with external code, be it in your awesomeService or in your catchAllAuthUtils.

This is how to use it:

const unsubscribe = store.watch(
  (state, getters) => {
    return [state.count, getters.getCountPlusOne];
  },
  watched => {
    console.log("Count is:", watched[0]);
    console.log("Count plus one is:", watched[1]);
  },
  {}
);

// To unsubscribe:
unsubscribe();

What we are doing is to call the watch method with two functions, one to return what part of the state and/or getters we want to keep an eye on and the other with the function that we want to invoke when state.count or getCountPlusOne change.

This is extremely useful to integrate with react code or angular or even... JQuery!

See the example in this CodeSandbox.

# SubscribeAction

Sometimes instead of watching a store property change it's more useful to react to a specific action, login and logout come in mind, vuex has us covered with subscribeAction.

Calling subscribe adds a 'callback' that is run at every action and that we can use to call custom code.

Let's use it to start and stop a global spinner before and after every action!

const unsubscribe = store.subscribeAction({
  before: (action, state) => {
    startBigLoadingSpinner();
  },
  after: (action, state) => {
    stoptBigLoadingSpinner();
  }
});

// To unsubscribe:
unsubscribe();

Don't miss out anything about Vue, your favourite framework.

Subscribe to receive all the articles we publish in a concise format, perfect for busy devs.

Related Articles

Creating a Store without Vuex in Vue.js 2.6

Tip on creating a simple store in Vue.js 2.6 by using the new Observable API

Alex Jover Morales

Alex Jover Morales

Feb 17, 2019

The new Provide and Inject in Vue 3

Getting stuck into the prop drilling? Learn how provide/inject can make your components more flexible and independent in this short tutorial.

Anthony Konstantinidis

Anthony Konstantinidis

Jul 18, 2022

The 101 guide to Script Setup in Vue 3

Don't you know about Script Setup yet? Check out this short article now and learn the nicest way to define a Vue component right now!

Anthony Konstantinidis

Anthony Konstantinidis

Jun 20, 2022

Sponsors

VueDose is proudly supported by its sponsors. If you enjoy it, consider supporting it to ensure the project maintainability.

Silver
Learning Partner