Some knowledge about vuex

core concept

The main core concepts in Vuex are as follows:
State
Mutation
Action
Getter

State

State provides the only common data source, all shared data must be unified in the State of the Store for storage

//创建Store数据源,提供唯一的公共数据
const store = new Vuex.Store({
    
    
  state: {
    
    
    count: 0,
  },
});

The way to access the data in State in the component is:
①this.$store.state.Global data name
②Use mapState to map, the following are the specific steps.

//1.从Vuex中按需导入mapState函数
import {
    
     mapState } from "vuex";

Map the global data required by the current component to the computer calculated properties of the current component through the imported mapState function

 //2.将全局数据,映射为当前组件的计算属性
    computed: {
    
    
        ...mapState(['count'])
    }

In Vuex, components are not allowed to directly modify the data in the store! !

Mutation

Mutation is used to change the data in the Store.
Store data can only be changed through mutation, and data in the store cannot be manipulated directly.
In this way, although the operation is a little cumbersome, it can centrally monitor the changes of all data.

// 定义Mutation
const store = new Vuex.Store({
    
    
  state: {
    
    
    count: 0,
  },
  mutations: {
    
    
    madd(state) {
    
    
      // 变更状态
      state.count++;
    },
  },
});

The first way to trigger mutation

  // 触发mutation
    methods:{
    
    
        handlel(){
    
    
            // 触发mutation 的第一种方式
            // $store提供的commit触发mutation中函数的方法
            this.$store.commit('madd')
        }
    }

Only the functions in the mutation have the right to modify the data in the state

Pass parameters when calling mutation:

// 定义Mutation
const store = new Vuex.Store({
    
    
  state: {
    
    
    count: 0,
  },
  mutations: {
    
    
    //第一个参数都是state
    addN(state, step) {
    
    
      // 变更状态
      state.count += step;
    },
  },
});
    // 触发mutation
    methods: {
    
    
        handle2 () {
    
    
            // 在调用commit函数,
            // 触发mutation时携带参数
            this.$store.commit('addN',3)
        }
    }

The second way to trigger mutation

 // 1.vuex中按需导入 mapMutations 函数
    import {
    
    mapMutations} from 'vuex

Map the required mutations function to the methods of the current component through the imported mapMutations function

    // 2.将指定的mutations函数,映射为当前组件的methods函数
    methods:{
    
    
        ...mapMutations(['madd','addN'])
    }

Asynchronous operations cannot be written in mutations

Action

Action is used to process asynchronous tasks;
if you change data through asynchronous operations, you must use Action instead of Mutation, but you still need to indirectly change the data by triggering Mutation in Action.

// store.js
// 定义Action
const store = new Vuex.Store({
    
    
  state: {
    
    
    count: 0,
  },
  mutations: {
    
    
    madd(state) {
    
    
      state.count++;
    },
  },
  actions: {
    
    
    addAsync(context) {
    
    
      setTimeout(() => {
    
    
        context.commit("madd");
      }, 1000);
    },
  },
});
    // 对应组件中
    methods: {
    
    
        handle() {
    
    
            // 这里dispatch 函数,专门用来触发action
            // dispatch触发actions 的第一种方式
            this.$store.dispatch('addAsync')
        }
    }

In actions, you cannot directly modify the data in the state. If you want to modify it, you must trigger a mutation through context.commit(). In other words, action does not have the right to modify state

Carry parameters when triggering actions asynchronous tasks

this.$store.dispatch() is the first way to
trigger actions ; the second way to trigger actions:

    // 1.vuex中按需导入 mapActions 函数
    import {
    
    mapActions} from 'vuex

Map the required actions function to the methods of the current component through the imported mapActions function:

// 将全局store中的某个actions方法映射为methods方法
// 使用映射方法时,既可以直接使用,也可以声明一个函数,将其引入使用。如果被映射的函数是一个带参数的函数,可以直接将参数写入
    ...mapActions(['addAsync','addNASync'])

Getter

Getter is used to process the data in the Store to form new data.
It does not modify the original data in the state, but only serves as a package.
① Getter can process the existing data in the Store to form new data, similar to the calculated properties of Vue.
② After the data in the Store changes, the data of the getter will also change.

// 定义getter
const store = new Vuex.Store({
    
    
  state: {
    
    
    count: 0,
  },
  getters: {
    
    
    showNum: (state) => {
    
    
      return "当前最新的数量是【" + state.count + "】";
    },
  },
});

The first way to use getters:
this.$store.getters. name
The second way to use getters:

    import {
    
     mapGetters } from 'vuex'
    // 可以将Getters中的内容映射到computed中
    computed: {
    
    
        ...mapGetters(['showNum'])
    }

For the sake of simplicity, Vuex provides four auxiliary function methods to easily integrate these functions into components.

  1. mapState
  2. mapGetters
  3. mapMutations
  4. mapActions

Sample code:

import {
    
     mapState, mapGetters, mapMutations, mapActions } from 'vuex'

export default {
    
    
    // ...
    computed: {
    
    
      localComputed () {
    
     /* ... */ },
        // 使用对象展开运算符将此对象混入外部对象中
      ...mapState({
    
    
        // 为了能够使用 `this` 获取局部状态,必须使用常规函数
        count(state) {
    
    
          return state.count + this.localCount
        }
      }),
      ...mapGetters({
    
    
        getterCount(state, getters) {
    
    
          return state.count + this.localCount
        }
      })
    }
    methods: {
    
    
      ...mapMutations({
    
    
          // 如果想将一个属性另取一个名字,使用以下形式。注意这是写在对象中
           add: 'increment' // 将 `this.add()` 映射为`this.$store.commit('increment')`
        }),
      ...mapActions({
    
    
          add: 'increment' // 将 `this.add()` 映射为 `this.$store.dispatch('increment')`
        })
    }
}

If you don't want to change the name after incorporating it into the component, you can use the array directly.

methods: {
    
    
    ...mapActions([
      'increment', // 将 `this.increment()` 映射为 `this.$store.dispatch('increment')`

      // `mapActions` 也支持载荷:
      'incrementBy' // 将 `this.incrementBy(amount)` 映射为 `this.$store.dispatch('incrementBy', amount)`
    ]),
}

Usually, we need to use a utility function to merge multiple objects into one so that we can pass the final object to the computed property. But with the object expansion operator, we can simplify the wording.




vuex state persistence, vuex-persistedstate

When you use Vuex, as long as the browser is refreshed, the Vuex data will be lost. It is inconvenient to manually store it in the local cache every time. There is a small plug-in that can maintain the persistence of Vuex.

Everyone knows the principle, which is to save localStorage. Usage

vuex-persistedstate vuex-persist

Today, I will briefly talk about vuex-persistedstate because this is relatively simple and easy to lose.

vuex-persistedstate uses the browser's local storage to persist the state. This means that refreshing the page or closing the tab will not delete your data.

First install

npm install vuex-persistedstate --save-dev

Introduced in index.js in the store folder

import createPersistedState from 'vuex-persistedstate'

Initialize vuex to add the plugin

const store = new Vuex.Store({
    
    
  modules: {
    
    
    user,
    groupBuying,
    clearance
  },
  getters,
  plugins: [createPersistedState()]
})

The default storage method is localStorage, because this project needs to be changed to the storage method of sessionStorage, change it in the configuration, if there are other configurations, you can refer to the official api

plugins: [createPersistedState(
    {
    
     storage: window.sessionStorage }
  )]

Come here first, click like and follow a wave~~Trojan Horse

Guess you like

Origin blog.csdn.net/weixin_53687450/article/details/112544221