Through a small demo (TODOS) of VUEX, analyze the knowledge points needed to be mastered;

1. Why Vuex

When developing with Vue, we often come across a state that can be used across multiple components, so that there is a core repository store in VUEX to store this state and other components can access it together.

1.1 Vuex schematic diagram

  • In the absence of actions:
  1. State –> data
  2. Get data: getters –> computed
  3. Change data: mutations –> methods

The view can change the data in state by clicking on an event that triggers the methods in Mutations. Once the state data changes, getters reflects the data to the view. Actions, then, can be understood to handle asynchrony and simply add another layer.

  • Now that we have mutions, actions, we have to say commit, dispatch, what does that do?
  1. In the VUE example, methods in Methods are triggered by a click event.
  2. When there is asynchrony, and dispatch is required in VUex to trigger methods in Actions, commit in Actions can trigger methods in mutations.
  3. When synchronization exists, commit directly in the component triggers the methods in VUEX.

2. Initial use of Vuex

  • 2.1 store warehouse

At the heart of Vuex is the repository Store, an instance of which is injected into all child components. When creating a project, select Store.

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

Vue.use(Vuex)

export default new Vuex.Store({
  state: {

  },
  mutations: {

  },
  actions: {

  }
})

Copy the code
  • 2.2 the State

The state property in store holds the desired state.

export default new Vuex.Store({
  state: {
    key:'all'
  },
})
Copy the code

The above code is in store/index.js;

How does the component get the key? We can calculate the property to get the key:

export default { data() { }, computed: { key() { return this.$store.state.count; }}}Copy the code

Because the store option is registered in the root instance, the store instance is injected into all the children of the root component, which can be accessed through this.$store. By evaluating attributes, we can use template syntax to call key from within the template, as follows:

<template>
  <div>
    <p>{{ key }}</p>
  </div>
</template>
Copy the code
  • 2.2.1 mapState

In order to obtain the key value, computed attributes are used. Sometimes, multiple states need to be obtained, but it is troublesome to use computed attributes for multiple times. In this case, the mapState method is used to obtain the state in the state, for example, to obtain the key from the component

Using mapState needs to be introduced in the component

import { mapState } from 'vuex' export default { data() { }, computed: { ... mapState(['key']) } }Copy the code

It’s easy and easy to write, and avoid repeating code, so you can take the key from the store and apply it to the template;

  • 2.3 Mutations

When we need to change the state in store, we do not change them directly in the component, but change them through mutation, which is convenient to track the state change. For example, change the key value

mutations:{
     changeKey(state,newKey) {
           state.viewKey = newKey
    }
Copy the code

In the other component, we trigger the change by defining methods and binding time, using commit:

() {new value (' changeViewKey ',' CCC ') {new value (' changeViewKey ',' CCC ')}Copy the code
  • 2.3.1 mapMutations

The previous several functions are the same, are to simplify the call, using the method as follows:

import { mapMutations } from 'vuex' export default { data() { }, methods: {// Map 'this.changeViewKey()' to 'this.changeViewKey'... mapMutations({changeViewKey:'changeKey'}) } }Copy the code
  • 2.4 the Action

Action is similar to mutation, except that:

The Action commits mutation rather than a direct state change. Actions can contain any asynchronous operation. Mutation can only contain synchronous transactions, so you need Action to handle asynchronous transactions. The Action controls the asynchrony process, and then calls the methods in mutation to change the state.

state:{
    list:[]
}
Copy the code

Define a method in mutations

init(state,data){
    state.list=data
}
Copy the code

Defined in action:

Actions :{// This context is an object with the same methods and attributes as the store instance getList(context) {// Asynchronously request data axios.get(' URL ').then(({data}) => {// Context.com MIT ('initList', data)})}Copy the code

This assigns the requested data to the list array in state

If we want to use a list array in a component, we can trigger actions in created and then use… MapState [‘list’] is used in templates

  created() {
    this.$store.dispatch('getList')
  },
Copy the code
  • Against 2.4.1 mapActions
import {mapActions} from 'vuex'; export default { // ... methods: { ... MapActions (['increment', // Map 'this.increment()' to 'this.$store.dispatch('increment')' // 'mapActions' also supports payloads: 'incrementBy' // map 'this.incrementBy(amount)' to 'this.$store.dispatch('incrementBy', amount)']),... MapActions ({add: 'increment' // map 'this.add()' to 'this.$store.dispatch('increment')'})}}Copy the code
  • 2.5 Getters

A getter is a common extracted part of state processing. When the state needs to be filtered, we can use the getter processing and then return it to the component. It does not change the information of the original array, but returns a new array.

export default new Vuex.Store({
  state: {
    list: [1, 2, 3, 4, 5, 6, 7, 8]
  },
});
Copy the code

We want to filter out even numbers in the array and then use them in the component, so the filtering can be done in the getter.

Getters :{// This is mainly the handling of the state, OushuArr (state){return state.list.filter((item) => {return item % 2 == 0})}, Call oushuArr to calculate the length getLength(state, getter) {return getter.oushuarr.length; }}Copy the code

Then call the getter in the computed value of the other component to get the desired state

computed: { list() { return this.$store.getters.oushuArr; }, length(){ return this.$store.getters.getLength; }}Copy the code
  • 2.5.1 mapGetters

The mapGetters helper function simply maps the getters in the store to local computed properties. When we want to introduce multiple getters into a component, we can use mapGetter:

import {mapGetters} from 'vuex'; export default { computed: { ... MapGetter (['oushuArr', 'getLength']) mapGetter({Arr:'oushuArr', length:'getLength'}) } }Copy the code

Call from inside a template using:

<template> <div> <h2>mapGetters </h2> {{ getLength }}</p> <ul> <li v-for="(item, index) in oushuArr" :key="index">{{ item }}</li> </ul> </div> </template>Copy the code

The above is the basic use of Vuex. Please refer to the Vuex document if you do not understand part of it