关于 Vuex 状态机的使用,可以分为两种方式:
- 操作主仓库
- 操作仓库模块
在一个项目中,可以同时使用主仓库和仓库模块来管理数据和方法。
一、主仓库
1、主仓库中设置数据和方法
export default new Vuex.Store({state: {},getters: {},mutations: {},actions: {}})
2、组件中获取数据和方法
组件中获取仓库中的数据和方法,有两种方式可以选择:
- 原生方式(不使用辅助函数)
- 辅助函数
1)原生方式(不使用辅助函数)
export default {computed: {计算属性名() {// 获取 state 数据return this.$store.state.数据名;},计算属性名() {// 获取 getters 数据return this.$store.getters.数据名;}},methods: {方法名() {// 调用 mutations 的方法this.$store.commit('方法名', 传值)},方法名() {// 调用 actions 的方法this.$store.dispatch('方法名', 传值)}}}
2)辅助函数
import { mapState, ... } from 'vuex';export default {computed: {...mapState(['数据名']), // 获取 state 数据...mapGetters(['数据名']) // 获取 getters 数据},methods: {...mapMutations(['方法名']), // 获取 mutations 方法...mapActions(['方法名']), // 获取 actions 方法}}
二、仓库模块
1、仓库模块中设置数据和方法
模块创建好后,需要在主仓库中引入:export default {namespaced: true,state: {},getters: {},mutations: {},actions: {}}
import 模块 from './modules/模块.js'export default new Vuex.Store({state: {},getters: {},mutations: {},actions: {},modules: {模块名: 模块}})
2、组件中获取模块的数据和方法
1)原生方式(不使用辅助函数)
export default {computed: {计算属性名() {// 获取指定模块中的 state 数据return this.$store.state.模块名.数据名;},计算属性名() {// 获取指定模块中的 getters 数据return this.$store.getters['模块名/数据名'];}},methods: {方法名() {// 调用指定模块的 mutations 的方法this.$store.commit('模块名/方法名', 传值)},方法名() {// 调用指定模块的 actions 的方法this.$store.dispatch('模块名/方法名', 传值)}}}
2)辅助函数
如果我们在一个组件中,要通过辅助函数获取多个模块中的数据和方法时:import { createNamespacedHelpers } from 'vuex';const { mapState, mapActions } = createNamespacedHelpers('模块名');export default {computed: {...mapState(['数据名']),...mapGetters(['数据名'])},methods: {...mapMutations(['方法名']),...mapActions(['方法名']),}}
import { createNamespacedHelpers } from 'vuex';const { mapState, mapActions } = createNamespacedHelpers('模块名一');const { mapState: 模块名二State, mapActions: 模块名二Actions } = createNamespacedHelpers('模块名二');
