Build an Online Shop with Vue

State Management

Vuex is a centralized state management Vue dependent library. What Vuex does for you is, rather than coordinate state's data in components, you can coordinate them in a huge state object and pass them down a state portion to whatever component needs a portion of the state.

The term state here, as we mentioned already is just an object. It can get giant depending on the size of the project. Giant or small, it's basically:

{}

Before we start creating and managing state, let's install and configure Vuex:

npm install --save vuex

Just like every other plugin, you need to configure Vue with Vuex:

// ./src/store/index
import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

State

Let's create our app's state with the initial data:

// ./src/store/index
export default new Vuex.Store({
  strict: true,
  state: {
    // bought items
    cart: [],
    // ajax loader
    showLoader: false,
    // selected product
    product: {},
    // all products
    products: [],
    // all manufacturers
    manufacturers: []
  }
})

Remember, a state is just an object. This time it contains all the initial data that our app is going to need.

You need to be able to access the store state and methods from a component instance. To do so, let's attach the store to the Vue instance

// ./src/main
import Vue from 'vue'
import store from './store'
//...
new Vue({
  el: '#app',
  store,
  // ...
})

This way you can access cart from the component, thus:

this.$store.state.cart

You can also retrieve the value of cart using getter store methods. Let's see how.