1. Definition of Vuex

Vuex is a state management mode developed specifically for vue.js applications

2. Vuex role

When multiple components need to access a variable at the same time, Vuex can easily meet this requirement

3. Configuration before using Vuex

(1) Install Vuex NPM

(2) Create a new folder named Store and create an index.js file in store

The code is:

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

// 1. Install plug-ins
Vue.use(Vuex)

// 2. Create objects
const store = new Vuex.Store({
    state: {},
    mutations: {},
    actions: {},
    getters: {},
    modules: {}})//3. Export store exclusive

export default store
Copy the code

(3) Mount it in main.js

An example diagram of Vuex

It can be clearly seen from the figure that state can be used for multiple interfaces, but to modify state, it needs to be modified through Mutations, not directly in the component, because devTools will not be able to track the modification of state, and if there is a problem in the future, it cannot be clearly seen which interface has modified state. Actions handle asynchronous operations, mainly back-end requests. The meaning of the objects created above will be analyzed one by one.

The five core attributes of VUEX

4.1 the state

A place to store state, similar to data

4.2 Mutations (Asynchronous operation cannot be implemented)

Used to modify the state, as shown in the figure

Call:

When you need to pass parameters, for example, you need to click a button to make conter add five and another conter add ten.

4.3 Actions (For asynchronous operations)

Here’s an example of what happens if you need to change the name property in person after a second

First we put this method in mutation

Although the data is rendered, there is no change in vue-devtool

So we need to put asynchronous operations in actions:

Vue-devtool also updates data normally

So asynchronous actions are performed within actions, including data requests and so on. The mutation method is called with commit, but the action method is called with display.

4.4 getters

Similar to how computed properties are invoked in VUE:

this. $store. Getters. Method nameCopy the code

4.5 modules

Because VUex is a single state tree, there is only one store instance, but sometimes it will be bloated if there are too many states, so we need modules to divide modules, so that we can separate the data of each module

Call a method, such as a

this.$store.state.a.
Copy the code

Since a is placed in state, the other calls are similar to mutation calls

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

Therefore, each module must be named differently