Vuex usage and instructions

1. state: storage data state;

2. Mutations: The method to modify the state must be a synchronous method;

3. Actions: Methods used to trigger asynchronous operations;

4. Getters: Methods for calculating and filtering data status;

5. Modules: Split the store into multiple modules.

2. store.commit(mutationName, payload): used to call mutation. The first parameter is the name of the mutation, and the second parameter is payload. It can be a parameter or an object named payload. payload can help us pass more parameter information.

3. store.dispatch(actionName, payload): used to call action. The first parameter is the name of the action. The second parameter is the same as commit. It can also be a parameter or named object payload.

4. store.getters.getterName: used to obtain the calculated properties defined in getters, where getterName is the name of the calculated property.

1. Create Vuex

// 引入 Vue 和 Vuex
import { createApp } from 'vue'
import { createStore } from 'vuex'

// 创建一个 Vuex 的 store
const store = createStore({
  state: {
    count: 0,
    message: []
  },
  mutations: {
    increment(value) {
      state.count = value
    },
    decrement(message) {
      state.message = message
    }
  },
  actions: {
    incrementAsync({ commit }) {
      setTimeout(() => {
        commit('increment')
      }, 1000)
    }
  },
  getters: {
    messageLength(state) {
      return state.message.length
    }
  }
})

2. Call the parameters in vuex

 1. Get the two parameter cases in the state

let count = this.$store.state.count

let message =  this.$store.state.message

2. To set the data of the two parameters in the state, you need to set the parameters through the dynamic function in vuex: the method defined in mutations

let value = 202
this.$store.commit('increment' ,value)


let message= [{name:'张三' ,age :23 } ,{ name:'李四' , age:24}]
this.$store.commit('decrement' ,message)

3. Get the value of the calculated attribute

let count = this.$store.getters.messageLength

4. Trigger an asynchronous method, and you can also pass parameters

this.$store.dispatch('incrementAsync')

3. If in VUE3 you can get parameter values ​​directly through Vuex’s computed

// 先导入vuex

import { useStore } from 'vuex'

//在setUp中创建vuex的应用

 setup() {
    const store = useStore()
    const count = computed(() => store.state.count)
    
     console.log(count)
   
  }

 

Guess you like

Origin blog.csdn.net/weixin_38826167/article/details/130019640