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

Setting up a full static Nuxt site

Overwhelmed by too many options to create a blog? Chill and use Nuxt, Storyblok and TailwindCSS to make it simple, beautiful and incredibly performant

Alex Jover Morales

Alex Jover Morales

Jul 14, 2020

Use Composition API to easily handle API requests in Vue.js

Not sure how to organize your API client in Vue.js? Learn this simple technique on how to do it using the new Composition API and make it easy.

Carlos Rodrigues

Carlos Rodrigues

Jul 6, 2020

Sponsors

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

Silver
StoryBlok
Learning Partner
Vue School