Vuex

Vuex provides a shared data store for components across all pages in your Vue site. Vue already has a method for passing data between parent and children (through props), but this can quickly become too complicated with many components and a tricky hierarchy in your site. Vuex makes it easy to manage a synchronized area with common data.

1) Install Vuex with npm

This may already be pre-installed in your project (if using the vue-cli or similar project starter).

npm install vuex --save

2) Create a store (shared area) with all of your data and functions

By convention, the file is named "store.js" and sits in the top of the src directory in your Vue project. The state object should contain key-value pairs that you want to use for component storage. The mutations field should contain functions for altering the values within state. Notice below the add function which adds a parameter to the total stored in state.

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

Vue.use(Vuex)

export default new Vuex.Store({
  state: {
    total: 0
  },
  mutations: {
    add (state, addValue) {
      state.total += addValue;
    },
  }
});

3) Inject the store into your app at the top level

This should go in your top level main.js file. Pretty simple- just import the store from the file you created and pass it into your new Vue instance.

import Vue from 'vue'
import App from './App.vue'
import store from './store'

let app = new Vue({
  store,
  render: h => h(App)
}).$mount('#app');

4) Use where needed!

Since the store is automatically injected into each Vue component, it can be accessed anywhere using this.$store. Below is an example where 1 is being added to the total contained in the store when a new component is created. Then the store total is printed to the console to log the total number of created components.

export default {
  created () {
    this.$store.commit('add', 1);
    console.log(this.$store.state.total);
  }
}