30 Days of Vue

Vuex

 

This post is part of the series 30 Days of Vue.

In this series, we're starting from the very basics and walk through everything you need to know to get started with Vue. If you've ever wanted to learn Vue, this is the place to start!

Vuex

With the knowledge of the Flux pattern and Vuex, let's integrate Vuex onto a Vue application to build on top of the things we've learned using a simple global store.

In the article before last, we saw how a simple global store allows us to manage application state in a reasonable manner that mimics the Flux pattern. Today, we'll reimplement the same application using the most robust and widely-used, flux-like, state management library in Vue - Vuex.

We'll look to build the same NumberDisplay and NumberSubmit component relationship that we've done before. As a refresher, we’ll want to build an implementation where an input is entered in a NumberSubmit component and that entered number is then shown in the template of a sibling NumberDisplay component.

Vuex

Since Vuex is an external library, it needs to be explicitly introduced into an application.

npm install vuex --save

For module based Webpack Vue applications, global level functionality (i.e. plugins) like Vuex need to be called with the Vue.use() global method prior to its use. The following code and the rest of the Vuex store instantiation can be done in a src/store.js file.

import Vue from 'vue';
import Vuex from 'vuex';

Vue.use(Vuex);

The heart of a Vuex integration is the Vuex Store which can be created with the new Vuex.Store({}) constructor. We can create the constructor and assign it a const variable we'll call store. We'll export the store variable since we'll need to include it in the application Vue instance shortly.

import Vue from 'vue';
import Vuex from 'vuex';

Vue.use(Vuex);

export const store = new Vuex.Store({  
  // store properties
});

The Vuex Store is made complete with 4 objects - state, mutations, actions, and getters.

State is simply an object that contains the data that needs to b