Last time, I learned the use of VUe-Router, which enabled me to switch between different pages and set up the page. This time, we will learn the state management mode of VUE — VUex. It is similar to the global state that Redux applies.

Note: This article is just a personal understanding of VUEX learning. To master it deeply, you need to read the official documents carefully.

1. Basic introduction

Vuex is a state-management mode plug-in developed specifically for vue.js SPA single-page component-based applications. Due to the modularity of the Vue SPA application, each component has its own data (state), interface (view), and method (Actions). These data, interfaces, and methods are distributed across components, and as the project content grows, the state in each component becomes difficult to manage. This is where vuex comes in handy. Let’s look at a simple vuex example.

1. Status of a single component

It is easy to change the interface view in a single component by simply changing the state data source. The following code:

<template>
    <div>
      view: {{ count }}
      <button @click="increment">increment</button>
    </div>
</template>

<script>
export default {
  // state
  data () {
    return {
      count: 0}},// actions
  methods: {
    increment () {
      this.count++
    }
  }
}
</script>Copy the code

So, the schematic in a single component looks like this:





Schematics in a single component

2. States in multiple components

However, as a componentized SPA application, we are bound to involve communication between multiple components. For example, if you have two identical components A and B, they share A count and each has A method to manipulate that count, which we write using vuex. Code for component A and component B (same code)

<template>
  <div>
    {{ $store.state.count }}
    <button @click="increment">increment</button>
  </div>
</template>

<script>
  export default {
    methods: {
      increment () {
        this.$store.commit('increment')}}}</script>Copy the code




Results 1





The results of 2

Increment = increment; increment = increment; increment = increment; increment = increment; As shown in the official schematic diagram below, we extract the global data source state, method mutations for changing the data source, and asynchronous operation method Actions into the store, realizing the independent management of the global data state.





Vuex official schematic diagram

Two, installation & configuration

1. Install vuex

Install directly using NPM

npm install vuexCopy the code

Configure package.json installation

  "devDependencies": {..."vuex": "^ 2.1.1". },Copy the code

2. The configuration

The configuration mode is similar to that of routes

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

Vue.use(Vuex)
// Create a Store instance
const store = new Vuex.Store({
  // Store status values
  state: {
    ...
  },
  // State value change method, operation state value
  Submit mutations is the only way to change the status of Vuex
  mutations: {
    ...
  },
  // Define getters in store (think of it as the store's calculated property). Getters accepts state as its first functiongetters: { ... }, actions: { ... }})// To change the status value, you can only do this by submitting mutations

/* eslint-disable no-new */
new Vue({
  el: '#app',
  template: '<App/>',
  components: { App },
  // Inject the Store instance into all the children of the root component
  store
  // The child uses this.$store to Orient the store
})Copy the code

3. Core Concepts

1. state

State is the global state (data source), and we can get the Vuex state template in the Vue component in the following way

  <div>
    {{ $store.state.count }}
  </div>Copy the code

script

console.log(this.$store.state.count)Copy the code

2. getters

Getters can be thought of as a calculated property of store, and is used in much the same way as a calculated property. Define getter:

  getters: {
    done(state) {
      return state.count + 5; }},Copy the code

The use of getter

console.log(this.$store.getters.done)Copy the code

3. mutations

Mutations is the only method to manipulate state, that is, only mutations method can change the value of state.

3.1 Basic Operations

Mutations operate on state

const store = new Vuex.Store({
  state: {
    count: 1
  },
  mutations: {
    increment (state) {// Change the statestate.count++
    }
  }
})Copy the code

The component requests a change in state by committing mutations

this.$store.commit('increment')Copy the code

The advantage of this is that we can track every state change, so that we can analyze and solve problems in time.

3.2 Submitting a Payload

Mutations method can be applied, and the specific usage is as follows:

Mutations: {// Submit the Payload add(state, n) {
      state.count += n
    }
  },Copy the code
this.$store.commit('add'.10)Copy the code

In most cases, the payload should be an object so that it can contain multiple fields and the mutation recorded will be easier to read.

3.3 pay attention to

The mutations method must be a simultaneous method!

4. actions

4.1 Basic Operations

We said that the mutations method must only be a synchronous method, but in order to handle the asynchronous method, actions appears. The differences between Action and mutations are as follows:

  • The Action commits mutation rather than a direct state change.
  • Actions can contain any asynchronous operation.
  • The Action still has to change the state using the mutation method

    As for the previous method, we use synchronous and asynchronous action respectively to verify the differences between mutations and the above mentioned methods:
    actions: {
      increment (context) {
        context.commit('increment')},incrementAsync (context) {
        // Delay 1 second
        setTimeout(() = > {context.commit('increment')},1000)}},Copy the code

    Instead of mutations using commit, Actions uses dispatch.

    this.$store.dispatch('incrementAsync')Copy the code

4.2 the context

Context is an object that has the same methods and properties as a Store instance. State and getters can be obtained by context.state and context.getters.

4.3 Distribution in payload form

    incrementAsyncWithValue (context, value) {
      setTimeout((a)= > {
        context.commit('add', value)
      }, 1000)}Copy the code
this.$store.dispatch('incrementAsyncWithValue'.5)Copy the code

5. module

Using a single state tree causes all the states of the application to be concentrated into one large object. However, when the app gets big, the Store object becomes bloated. To solve these problems, Vuex allows us to split the Store into modules. Each module has its own state, mutation, Action, getters, and even nested submodules — a similar split from top to bottom:

const moduleA = {
  state: {... }, mutations: { ... }, actions: { ... }, getters: { ... } } const moduleB = {state: {... }, mutations: { ... }, actions: { ... } } const store = new Vuex.Store({ modules: { a: moduleA, b: moduleB } }) store.stateA // -> moduleA status store.stateB // -> moduleB statusCopy the code

Module is actually for large SPA applications. For the time being, I don’t have much knowledge about the application and understanding of Module. I will fill in this part later. To learn more about Modules, consult the official Module documentation

Vue.js learning series

Vue.js Learning series 1 — Vue-Router2 Learning Practice Notes (with DEMO) Vue.js learning series 2 — Vuex learning practice notes (with DEMO) Vue.js learning series 3 — Axios and network transport related knowledge learning practice

Vue.js learning series project address

Github.com/violetjack/…

About the author

VioletJack is a mobile and front-end engineer with two years of mobile experience and one year of front-end experience. Now focus on mobile front-end learning and development. Good at Android development and Vue front-end development. Regular blog posts on Android, Vue, mobile front end. Welcome to pay attention to me, I will attentively maintain and manage the blog, more output high-quality articles. At the same time, I also hope that what I wrote can help friends in need. Sina Weibo: github.com/violetjack Nuggets: juejin.cn/user/442409… CSDN: blog.csdn.net/violetjack0… Jane: www.jianshu.com/users/54ae4… Making: github.com/violetjack