返回

在 Vue 3 中管理 Vuex 4 Store 的指南:mapActions 和 mapGetters

vue.js

在 Vue 3 中使用 Vuex 4 的 mapActionsmapGetters

在 Vue 3 中,setup 函数让我们可以管理组件的内部状态和响应式属性,也带来了新的管理 store 的方式。在 Vuex 4 中,不再支持 mapStatemapGetters,而改用了 useMapper 助手函数。

使用 mapGetters

在 Vue 3 中使用 mapGetters,我们可以在 setup 函数中使用 useMapper 来访问 store 的 getter。

import { useMapper } from 'vuex'

const { mapGetters } = useMapper()

const getters = mapGetters('myModule', [
  'myStateVariable'
])

然后就可以在组件中使用 getters 对象:

const setup = () => {
  const getters = mapGetters('myModule', [
    'myStateVariable'
  ])

  // 使用 getters
}

使用 mapActions

同样,可以使用 useMapper 来访问 store 的 actions:

import { useMapper } from 'vuex'

const { mapActions } = useMapper()

const actions = mapActions('myModule', [
  'myAction'
])

然后可以在组件中使用 actions 对象:

const setup = () => {
  const actions = mapActions('myModule', [
    'myAction'
  ])

  // 使用 actions
}

使用 useStore

除了使用 useMapper,也可以直接使用 useStore 钩子来访问 store:

const store = useStore()

const getters = store.getters

// 使用 getters

替代方案

在 Vue 3 中使用 Vuex

另一种管理 Vuex store 的方法是直接使用 useStore 钩子:

import { useStore } from 'vuex'

const store = useStore()

// 直接使用 store

在 Vuex 4 中弃用 mapStatemapGetters

由于 Vuex 4 中模块的命名空间化,mapStatemapGetters 已被弃用。请改为使用 mapActionsmapGetters

常见问题解答

1. 为什么在 Vue 3 中使用 setup 函数?

setup 函数允许我们在组件创建时执行额外的操作,例如访问和管理 store。

2. useMapperuseStore 之间有什么区别?

useMapper 允许我们更方便地访问特定的 getters 和 actions,而 useStore 提供对整个 store 的直接访问。

3. Vuex 4 中模块的命名空间化是什么意思?

在 Vuex 4 中,模块被命名空间化,这意味着你需要在 mapActionsmapGetters 中指定模块的名称。

4. 我应该在 Vue 3 中使用 useMapper 还是 useStore

如果你需要访问特定的 getters 和 actions,则可以使用 useMapper。否则,如果你需要对整个 store 进行更直接的控制,可以使用 useStore

5. 如何在 Vue 3 中使用 Vuex?

在 Vue 3 中使用 Vuex 有多种方法,包括 useMapperuseStore 和直接通过 store。选择最适合你用例的方法。