Quickly learn Vue's state management mode - Vuex

Introduction to Vuex

When making a Vue project with a relatively large amount of engineering, we often encounter situations where each component needs to operate and call the same data.

In application, we can use props to obtain and transfer data between parent and child components, or use store mode. But the larger the amount of data, the more data sources that need to be managed, which is more suitable for the use of vuex.
Insert picture description here

Vuex Chinese official website: https://vuex.vuejs.org/zh/

According to the official statement: Vuex is a state management mode developed specifically for Vue.js applications. It uses centralized storage to manage the state of all components of the application, and uses corresponding rules to ensure that the state changes in a predictable manner.

Normal state management mode

Generally speaking, the state self-management application includes the following parts:

  • state, the data source that drives the application;
  • view, which maps state to view in a declarative manner;
  • actions, in response to state changes caused by user input on the view.
    Unidirectional data flow

But when there are multiple components in the project to call and modify these data states, this one-way data flow structure is easily destroyed

The reasons are as follows:

  • Multiple views depend on the same state. The method of passing parameters will be very cumbersome for multi-level nested components, and it is powerless for state transfer between brother components
  • Actions from different views need to change the same state. Often, multiple copies of the parent and child components are directly referenced or through events to change and synchronize the state. The above patterns are very fragile and often lead to unmaintainable code.

vuex management mode

Vuex is a global singleton mode to manage various data sources and states. In this mode, our component tree constitutes a huge "view", no matter where in the tree, any component can get state or trigger behavior.
By defining and isolating various concepts in state management and maintaining independence between views and states through mandatory rules, our code will become more structured and easier to maintain.

vuex installation

npm installation:npm install vuex

Vuex also supports <script></script>label import

In a modular packaging project, after using vuex, you need to use import to call vuex

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

Vue.use(Vuex)

If you use <script></script>labels, you don't need these procedures, just use them directly.

vuex core

State

For data that needs to be manipulated by multiple components, you can create vuex and write it into the state

After introducing Vuex into main.js in the vue cli project, create a Vuex.Store example, and write variable data in the state when defining

const store = new Vuex.Store({
    
    
  state: {
    
    
    data1: '可以被多组件操作的数据',
    ......
  }
})

The this.$store.state.data1variable value can be obtained in the component or its sub-components. In fact, the variable data1 can be directly modified in the sub-component, but this method is not recommended to modify the variable data in vuex. It is still recommended to use the latter Mutationand Actionto modify the variables.

<template>
    <div id="VuexTest2"> <div>组件2号: {
    
    {
    
     $store.state.data1 }}</div> </div>
</template>

<script>
export default {
    
    
    name:'VuexTest2',
    components: {
    
    },
    props: {
    
    },
    data() {
    
    
        return {
    
     };
    },
    created() {
    
    },
    mounted() {
    
    
        console.log(this.$store.state.data1)
    },
    watch: {
    
    },
    methods: {
    
     },
    computed: {
    
     }
};
</script>
<style scoped>

</style>

display effect:
Insert picture description here


Getter

Vuex allows us to define "getter" in the store (it can be thought of as a calculated attribute of the store). Just like a calculated property, the return value of a getter will be cached according to its dependencies, and will be recalculated only when its dependent value has changed.

const store = new Vuex.Store({
    
    
  state: {
    
    
    todos: [
      {
    
     id: 1, text: '...', done: true },
      {
    
     id: 2, text: '...', done: false }
    ]
  },
  getters: {
    
    
    doneTodos: state => {
    
    
    // 返回todos中done为true的对象
      return state.todos.filter(todo => todo.done)
    }
  }
})

It can be accessed through properties:Getter 会暴露为 store.getters 对象

this.$store.getters.doneTodos

effect:
Insert picture description here


Mutation

The only way to change the state in the Vuex store is to submit a mutation. Mutations in Vuex are very similar to events: each mutation has a string event type (type) and a callback function (handler).

Mutations can also add parameters and will accept state as the first parameter.

Note: Mutation must be a synchronous function

example:

const store = new Vuex.Store({
    
    
  state: {
    
    
    count: 0
  },
  mutations: {
    
    
    increment (state, payload) {
    
    
      // 变更state中的count
      state.count += payload.amount;
    },
  }
})

Component operation:

this.$store.commit('increment', {
    
     amount: 3 })

effect:
Insert picture description here


Action

Action is similar to mutation, except that:

  1. Action submits a mutation instead of directly changing the state.
  2. Action can contain any asynchronous operation.

example:

const store = new Vuex.Store({
    
    
  state: {
    
    
    count: 0
  },
  mutations: {
    
    
    increment (state) {
    
    
      state.count++
    }
  },
  actions: {
    
    
    increment (context) {
    
    
      context.commit('increment')
    }
  }
})

The action is triggered in the component, and the Action is triggered by the store.dispatch method

this.$store.dispatch('increment')

Must mutations execute this restriction synchronously. Asynchronous operations can be performed inside Action

actions: {
    
    
	incrementAsync ({
    
     commit }, payload) {
    
    
	   setTimeout(() => {
    
    
	     commit('increment', payload)
	   }, 1000)
	 },
 }

Module

Module is modular. Because of the use of a single state tree, all the states of the application will be concentrated into a relatively large object. When the application becomes very complex, the store object may become quite bloated.

Vuex allows us to divide the store into modules. Each module has its own state, mutation, action, getter, and even nested submodules-split in the same way from top to bottom.

const moduleA = {
    
    
  state: () => ({
    
     ... }),
  mutations: {
    
     ... },
  actions: {
    
     ... },
  getters: {
    
     ... }
}

const moduleB = {
    
    
  state: () => ({
    
     ... }),
  mutations: {
    
     ... },
  actions: {
    
     ... }
}

After the module is created, you can use module to load the previous module into vuex

const store = new Vuex.Store({
    
    
  modules: {
    
    
    a: moduleA,
    b: moduleB
  }
})

View the module status in the component

this.$store.state.a // -> moduleA 的状态
this.$store.state.b // -> moduleB 的状态



The above is a brief description of the basic functions and principles that vuex can master after a quick study. Of course, there are many other contents, and you need to dig a little bit in the process of use.
Insert picture description here

Guess you like

Origin blog.csdn.net/qq_36171287/article/details/115221865