SoFunction
Updated on 2025-04-04

Simple implementation of Store in Vuex

Simple implementation of Store in Vuex

After installing Vuex, let's create a store.

The creation process is straightforward - only one initial state object and some mutations are required:

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

(Vuex)

const store = new ({
  state: {
    count: 0
  },
  mutations: {
    add(state) {
      ++
    }
  }
})

Get the state object through and trigger the state change through the method:

('add')

(':' + ) // -> :1

In order to access this.$store property in the Vue component, you need to provide a created store for the Vue instance. Vuex provides a mechanism to inject the store from the root component to all child components in the form of store options:

// 

new Vue({
  el: '#app',
  store
})

Now we can submit a change from the component's method and then modify the count variable value in state:

methods: {
  add() {
    this.$('add')
    ('' + this.$)
  }
}

Why use mutation method to modify variables defined in state instead of directly modifying

  1. We submit mutation instead of directly changing it because we want to track changes in state more clearly.
  2. This simple convention can make your intention more obvious, so that you can more easily interpret state changes inside your application when you read the code.
  3. In addition, this also gives us the opportunity to implement some debugging tools that can record each state change and save state snapshots.

Since the state in the store is responsive, calling the state in the store in the component is so simple that it only needs to be returned in the computed attribute. Triggering changes is also just to submit mutations in the component's methods.

This is the end of this article about the simple implementation of Store in Vuex. For more related Store content in Vuex, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!