Summary of Vuex knowledge points

What is Vuex

Introduction: Vuex 是一个专为 Vue.js 应用程序开发的状态管理模式。
Adopt the state of all components in the centralized storage management application, suitable for the development of medium and large projects

Why use vuex

Since Vue is a one-way data flow, the communication between components relies on child to parent, parent to child, or to create an empty Vue instance to transfer parameters between brothers. With the development of medium and large projects, the more components More and more, the traditional mode of parameter transfer seems too cumbersome, so vuex came for this

Vuex workflow

The official gave a super perfect flow chart. ↓ The
Details are concise and easy to understand
most cumbersome workflow of vuex is also very easy to understand through this graph analysis. For example, if the
component wants to modify the state, call the method in actions through this. store. dispatch ("the method name in actions"), and call the actions in actions through this. store.dispatch("the method name in actions") In the method, pass this in actions.S T O R & lt E . D I S P A T C H ( " A C T I O n- S in the square method name " ) modulation with A C T I O n- S in the square method , the A C T I O n- S in through the through T H I S .store.commit("method name in mutations") calls the method in mutations, modifies the data in the state in the mutations, and changes in the data in the state will immediately respond to the component

Vuex uses the previous configuration

  • Install vueX↓
cnpm install vuex -S

Note:
-S is the abbreviation of -save, meaning: install the plug-in into dependencies (production environment dependency)
-D is the abbreviation of -save-dev, meaning: install the plug-in into devDependencies (development environment dependency)

  • Complete vuex code snippet↓ (create a store folder in src and create index.js in it)↓
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
export default new Vuex.Store({
    
    
  state: {
    
    
  },
  mutations: {
    
    
  },
  actions: {
    
    
  },
  modules: {
    
    
  }
})
  • Introduce it in main.js (the entry file of the vue project) and put it in the vue instance↓
import store from './store' //index.js可无需写入,vue会自动读取文件夹内的index.js文件
new Vue({
    
    
  router,
  store,
  render: h => h(App)
}).$mount('#app')

The core concept of vuex

Officially given by vue is that the core of every Vuex application is the store (warehouse).
However, five core concepts have emerged in the store, namely state, mutations, actions, getters, and modules.

state (single state tree — 状态)

State is where VueX stores data.
Vuex's state storage is responsive . When the Vue component reads the state from the store, if the state in the store changes, the corresponding component will be updated accordingly. Therefore, we usually put the data in the state into the computed (calculated attribute), and then return

  • Define the data in vueX in state↓
  state: {
    
    
    count:100,
    price:25
  }
  • Obtain and return from the calculated attributes.
    Whenever this.$store.state.count changes, the calculated attributes will be re-calculated and the associated DOM will be updated ↓
computed: {
    
    
    count () {
    
    
      return this.$store.state.count
    }
  }
  • Put the data returned in the calculated attribute in the template template↓
<p>{
   
   {count}}</p>

State can also be rendered in this way (not recommended)↓

<p>{
   
   {$store.state.count}}</p>

In this way, we will render the data in vuex to the template

mutations (status update — 事件)

Mutations are the only place that can manipulate data in state. The default first parameter in mutations is state, and the following data are all parameters we need to pass.

  • In the component by this.$store.commit('mutations中的事件名',参数)calling the method in mutations↓
  plus(){
    
    
    this.$store.commit("ADD",2)
  }
  • Finally operate in mutations↓
mutations: {
    
    
  ADD(state,val){
    
    
    state.count+=val
  }
}

actions (asynchronous)

Role: It is used to replace Mutation for asynchronous operation

  • Pass in the component this.$store.dispatch("actions中的方法名",参数)to call the method in actions↓
plus(){
    
    
this.$store.dispatch("GOADD",5)
}
  • Call the method in mutations in actions (the default first parameter in actions points to store (there are two alternatives to this parameter: 1.context 2.{commit}), and then all the parameters we need to pass)
  • Solution one ↓
GOADD(store,val){
    
    
  store.commit("ADD",val)
}
  • Plan two↓
GOADD(context,val){
    
    
  context.commit("ADD",val)
}
  • Plan three↓
GOADD({
    
    commit},val){
    
    
  commit("ADD",val)
}
  • Change state data in mutations
ADD(state,val){
    
    
  state.count+=val
}

getters (calculation)

This method is similar to computed (calculated attributes), and the data in the state can be further processed

  • Calculate the state in the getters↓
sum(state){
    
    
  return state.count * state.price
}
  • Return getters in computed↓
 sum(){
    
    
   return this.$store.getters.sum
 }
  • Render in the template↓
<p>{
   
   {sum}}</p>

This method is still not recommended↓

<p>{
   
   {$store.getters.sum}}</p>

modules

Prerequisite for use: When our project uses too much data in vuex, the code size is too large, which is not conducive to maintaining
Vuex. Allow us to divide the store into modules. Each module has its own state, mutation, action, and getter.

  • Create modules ↓
const modulesA={
    
    
  state:{
    
    
  	count:1000
  },
  actions:{
    
    },
  getters:{
    
    },
  mutations:{
    
    
	ADD(state){
    
    
	state.count++
	}
  }
}
const modulesB={
    
    
  state:{
    
    },
  actions:{
    
    },
  getters:{
    
    },
  mutations:{
    
    }
}
export default new Vuex.Store({
    
    
  modules: {
    
    
    MA:modulesA,
    MB:modulesB
  }
})
  • The state data in the mudules module is called in the component, and the data is still returned in a wave in the calculated, and the method MAin the mutations in the module is called
//computed计算属性中   
 number(){
    
    
   return this.$store.state.MA.count  //获取MA模块中state里面的count数据
 }
 //methods方法模块中     
 add(){
    
    
 this.$store.commit("ADD")   //调用MA模块中mutations里面的ADD方法
 }

Summary:, this.$store.state.'模块名'.'此模块state中的数据名'in the MAmodule getters: "I am the same"
this.$store.commit("模块中mutations中的方法名"), in the MAmodule actions: "I am the same"

ES6 modular

This method, I personally feel that it is more conducive to maintenance and development, and can greatly reduce the amount of code for a single js (index.js under the store folder) file, making the code look less bloated.

  • The method is as follows ↓
    Create state.js, mutations.js, getters.js, actions.js files in the store folder, and import the
    column in the index.js file : the content in state.js, other js files: "我也The same"↓
const state={
    
    
  count:1000
}
export default state

Column: index.js↓

import Vue from 'vue'
import Vuex from 'vuex'
import state from "./state"
import mutations form "./mutations"
import actions form "./actions"
import getters form "./getters"
Vue.use(Vuex)
export default new Vuex.Store({
    
    
  state,
  mutations,
  actions,
  getters,
  modules:{
    
    
    //TODO
  }
})

The state above is the abbreviation of state: state, es6 stipulates that the attribute name and the attribute value name are the same, but it can be abbreviated as a single name
. Although there are more files, the amount of code for a single js file is less. If you think it is OK, you can refer to it^ ( #^. ^#) ^
Of course, it can also be used in conjunction with modules in vueX.
And look at the following code, the test is effective (create a modulesA.js in the store folder and export it)↓
index.js code↓

import Vue from 'vue'
import Vuex from 'vuex'
import ModulesA from "./modulesA"
Vue.use(Vuex)
export default new Vuex.Store({
    
    
  modules:{
    
    
    MA:ModulesA
  }
})

modulesA.js code↓

import state from "./state"
const modulesA={
    
    
state
}
export default modulesA**

state.js code↓

const state={
    
    
  count:1000
}
export default state

At this point, the built-in core of vueX has been finished, and then I will go to dessert ↓看下方标题

Auxiliary functions in vueX

vueX the syntactic sugar mapState, mapActions, mapMutations, mapGetters
when a component needs multiple states, these states are declared property too long to calculate. So there are auxiliary functions.

<template>
  <div class="home">
    <p>{
    
    {
    
    num}}</p>
    <button @click="ADD">加一</button>
  </div>
</template>

<script>
//导入vueX中mapState、mapMutations、mapGetters、mapActions的语法糖
import {
    
    mapState,mapMutations,mapGetters,mapActions} from "vuex"
export default {
    
    
  name: 'Home',
  computed:{
    
    
    ...mapState({
    
    num:'count'}),//也可以写成数组的形式,num是自定义名字,如若不自定义,可以写成数组的形式,参考mapMutations。
    ...mapGetters()
  },
  methods:{
    
    
    ...mapMutations(["ADD"]),//在模板的按钮中可以直接调用mutations中的方法。
    ...mapActions()
  }
}
</script>

Helper functions are used in conjunction with modules

  • Open the namespace in the module
let moduleA = {
    
    
  namespaced: true, //开启命名空间。
  state: {
    
    },
  actions: {
    
    },
  mutations: {
    
    },
  getters: {
    
    }
}
const store = new Vuex.Store({
    
    
  modules: {
    
    
  	moduleA
  },
  • Introduce the createNamespacedHelpers(namespace helper function) in vuex into the component , get the module name introduced in this function, and then you can use it happily. You can also rename it inside.

For example: when we use the public data in vuex in this component, but also use the data in the module, we can use renaming to solve

<template>
  <div id="app">
    {
    
    {
    
    count}}
      <button @click="add">点击</button>
  </div>
</template>
<script>
import {
    
    createNamespacedHelpers} from 'vuex'   //引入命名空间辅助函数
const {
    
    mapState:mapStateModuleA,mapActions:mapActionModuleA,mapMutations:mapMutationModuleA,mapGetters:mapGetterModuleA} = createNamespacedHelpers('moduleA')
export default {
    
    
  methods:{
    
    
    ...mapActionModuleA(),
    ...mapMutationModuleA({
    
    add:'ADD'})
  },
  computed:{
    
    
    ...mapStateModuleA(['count']),
    ...mapGetterModuleA()
  }
}
</script>

call! It's a lot simpler. The syntactic sugar of vuex is really amazing to me, and it really reduces the amount of code. nice!

VueX data persistence

Sometimes when we refresh the page, the data of vuex will become the data when it is initialized, so we need to save the state of the data in the state in vuex, so as to refresh the page, the data is still there.

  • Install vuex-persistedstateplugin
npm install vuex-persistedstate -S
  • Configure as follows
import createPersistedState from 'vuex-persistedstate'
const store = new Vuex.Store({
    
    
  state,
  mutations,
  actions,
  getters,
  plugins: [createPersistedState({
    
    
    storage: sessionStorage,
    key: "token"
  })]//会自动保存创建的状态。刷新还在
})

storage: storage method. ( sessionStorage, localStarage) Key: Define the key in the local storage

Guess you like

Origin blog.csdn.net/shiqina/article/details/114253995