Use of Vuex

foreword

What is Vuex?

The official documentation says this:

 Vuex 是一个专为Vue.js 应用程序开发的状态管理模式+ 库。它采用集中式存储管理应用的所有组件的状态,并以相应的规则保证状态以一种可预测的方式发生变化。

It can be understood that Vuex is a data management framework

what Vuex has

state (where state data is stored)

getters (can be understood as the computed properties of the store)

mutations (methods that change data in state (modify data synchronously))

actions (methods that change data in state (modify data asynchronously))

modules (when the state is too large, you can use modules to split it into modules)

Use of Vuex

 state: { // 我们在state 中定义一个count count: 0 }, // 在组件中使用import { useStore } from 'vuex' import { computed } from 'vue' export default { setup () { const store = useStore() const count = computed(() => store.state.count) return { count } } }

Modify the data in the state

 // 第一步使用dispatch 方法,派发一个action,名字为countAdd const countAdd = () => { store.dispatch('countAdd') } actions: { // 第二步, store 感知到触发了一个countAdd 的action ,执行countAdd 方法countAdd () { // 第三步,提交一个commit 触发一个mutation this.commit('countAdd') } }, mutations: { // 第四步,对应的mutation 被执行countAdd () { // 第五步,在mutation 里进行修改数据this.state.count++ } },

If the changed data has no asynchronous operation, you can also submit a commit directly to modify the data

 const countAdd = () => { store.commit('countAdd') } mutations: { // 第四步,对应的mutation 被执行countAdd () { // 第五步,在mutation 里进行修改数据this.state.count++ } },

Note: It is not recommended to write asynchronous operations in mutation

Pass parameters to modify

If the data we want to modify is not fixed, it can be modified by passing parameters

 const countAdd = () => { store.commit('countAdd', 10) } actions: { countAdd (store, num) { store.commit('countAdd', num) } }, mutations: { countAdd (state, num) { state.count += num } },

This article is reprinted from https://www.xxhzm.cn/index.php/archives/657/
This site is for inclusion only, and the copyright belongs to the original author.

Leave a Comment