前言

Vuex 是什么?

官方文档里面是这么说的:

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

可以理解为 Vuex 是一个数据管理框架

Vuex 都有什么

state(存放状态数据的地方)

getters(可以理解为 store 的计算属性)

mutations(改变 state 中数据的方法(同步修改数据))

actions(改变 state 中数据的方法(异步修改数据))

modules(当 state 过大时,可使用 modules 将其分割成模块)

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
    }
  }
}

修改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++
    }
  },

如果更改的数据,没有异步操作的话,也可以直接提交一个 commit 进行修改数据

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

注:mutation 内不建议写异步操作

传参进行修改

如果我们要修改的数据不是固定的,可以通过传参的方式进行修改

  const countAdd = () => {
    store.commit('countAdd', 10)
  }

  actions: {
    countAdd (store, num) {
      store.commit('countAdd', num)
    }
  },
  mutations: {
    countAdd (state, num) {
      state.count += num
    }
  },
最后修改:2023 年 08 月 27 日
如果觉得我的文章对你有用,请随意赞赏