Home  >  Article  >  Web Front-end  >  How to implement global state management in vuejs

How to implement global state management in vuejs

青灯夜游
青灯夜游Original
2021-09-08 13:53:103112browse

Vuex can be used to achieve global state management in vuejs; Vuex is a state management model specially developed for Vue.js applications. It can be used to manage global data and manage the data status of complex applications, such as Brother Communication of components, value passing of multi-layer nested components, etc.

How to implement global state management in vuejs

The operating environment of this tutorial: windows7 system, vue2.9.6 version, DELL G3 computer.

##vuex global state management

Vuex It is a state management pattern developed specifically for Vue.js applications. It can manage the data status of complex applications, such as communication between sibling components, value transfer among multi-layer nested components, etc.

In layman's terms, vuex is global data management, used to manage global data. Vue's original data management can only transfer data between parent and child components, and it is inconvenient. Use vuex for global data management. All data is stored in vuex and called when used.

The core of vuex:

    state
  • mutations
  • actions
  • getter

Usage of Vuex

Install and use vuex

Installation

1. Install in the project

npm install vuex --save

2. Create a new store.js file

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

Vue.use(Vuex)

const store = new Vuex.Store({
  state: {
      //存放初始数据
    count: 0
  },
  mutations: {
      //存放修改数据的方法
    increment (state) {
      state.count++
    }
  }
})

Use data

Method 1: Use $store call

Use this.$store.state directly in the component to call data

this.$store.state.数据名

Method 2: Import mapState, expand the data in the component and map it. It needs to be written to the calculated attribute. When using it, just write count

//先导入mapState
import {mapState} from 'vuex'

computed:[
    ...mapState(['count'])
]

When operating on data, the state data cannot be called directly. If you want to modify the data, you need to write a method in the mutation. The purpose is to make it easier to find where to find the problem.

The function and usage of Mutations

mutations is to write methods to operate on data

  mutations: {
//存放修改数据的方法
   add(state) {
     state.count++
   }
 }

Usage method one:

Trigger the mutations function, use commit to call the method name inside

this.$store.commit This is the first way to trigger mutations

methods:{
   handle(){
       this.$store.commit('add')
   }
}

mutations pass Two parameters can be passed in the parameter mutation method. The first is state, and the second is the custom parameter payload

  mutations: {
//存放修改数据的方法
   addN(state,N) {
     state.count+=N
   }
 }

The call is in the component method

methods:{
   handle2(){
       //触发mutation并传参
       this.$store.commit('addN',4)
   }
}

Use method two

Import the mapMutations function in vuex into the component

mapMutations(['sub']) is the comparison between the methods inside and The method in the store is mapped

...It is the expansion operator

import {mapMutations} from 'vuex'

methods:{
   //将方法名写在[]里  ['addN','sub']
   ...mapMutations(['sub'])
   btnhandle(){
       //调用时直接写this.方法名
       this.sub()
       //当传入参数时,直接写这个参数,不需要写state
       this.addN(4)
   }
}

Note: You cannot write asynchronous code in the Mutation function; for example, writing a timed function, although the page will change, but the actual status value will not change. So there is the usage of actions

Actions

Action is used to handle asynchronous tasks.

If the data is changed through asynchronous operation, it must be done through Action instead of Mutation. However, the data must still be changed indirectly by triggering Mutation in Action.

It is at the same level as mutations in the store. Write an actions:{ } call the mutations method in it, and then trigger Actions in the component

  mutations: {
  //存放修改数据的方法
    add(state) {
      state.count++
    }
  },
  actions:{
      //context是上下文
      addAsync(context){
          setTimeout(()=>{
              //调用add方法,actions中不能直接修改state中的数据,只有mutation有这个权力
              context.commit('add')
          })
      }
  }

Use actionsTo use dispatch in the component to trigger

btnHandle(){
    //dispatch专门触发action
    this.$store.dispatch('addAsync')
}

Transfer parameters in actions

Write formal parameters in store actions and mutations

  mutations: {
  //传参
    addN(state,n) {
      state.count+=n
    }
  },
  actions:{
      //context是上下文
      addAsync(context,n){
          setTimeout(()=>{
              //调用add方法,并传参
              context.commit('addN',n)
          })
      }
  }

Write actual parameters in components

btnHandle(){
    //dispatch专门触发action,并传入参数
    this.$store.dispatch('addAsync',5)
}

The second is to expand and map Introduce mapActions

//引入方法
import {mapActions} from 'vuex

methods:{
    //映射actions
    ...mapActions(['addAsync'])
    btnhandle(){
        //调用对应的actions
        this.addAsync()
    }
}
//也可以不写btnhandle方法了直接将映射的方法名写在点击操作上

Note: Call the actions method in the component, and use commit in actions to call the mutations method

getters

    Getter is used to process the data in the Store to form new data. The original data will not be modified
  • Getter can process the existing data in the Store to form new data, similar to Vue's calculated properties.
  • When the data in the Store changes, the Getter data will also change accordingly.
  • state:{
       count:0
    },
    getters:{
       showNum(state){
           return '当前最新的数据是:'+state.count
       }
    }

The first calling method: this.$store.getters.method Name

this.$store.getters.showNum

The second calling method: mapping expansion, mapping in computed

import {mapGetters} from 'vuex'

computed:{
   ...mapGetters(['showNum'])
}

Summary

  • state is used to store initial data and perform data initialization. It is best not to call state directly in the component
  • mutations which stores the data Methods for performing operations, but asynchronous operations cannot be performed
  • actionsThere are methods for performing asynchronous operations
  • getters are used for data in the Store Perform processing to form new data
Related recommendations: "

vue.js Tutorial"

The above is the detailed content of How to implement global state management in vuejs. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn