关于 Vuex 状态机的使用,可以分为两种方式:

  • 操作主仓库
  • 操作仓库模块

在一个项目中,可以同时使用主仓库和仓库模块来管理数据和方法。

一、主仓库

1、主仓库中设置数据和方法

  1. export default new Vuex.Store({
  2. state: {},
  3. getters: {},
  4. mutations: {},
  5. actions: {}
  6. })

2、组件中获取数据和方法

组件中获取仓库中的数据和方法,有两种方式可以选择:

  1. 原生方式(不使用辅助函数)
  2. 辅助函数

    1)原生方式(不使用辅助函数)

    1. export default {
    2. computed: {
    3. 计算属性名() {
    4. // 获取 state 数据
    5. return this.$store.state.数据名;
    6. },
    7. 计算属性名() {
    8. // 获取 getters 数据
    9. return this.$store.getters.数据名;
    10. }
    11. },
    12. methods: {
    13. 方法名() {
    14. // 调用 mutations 的方法
    15. this.$store.commit('方法名', 传值)
    16. },
    17. 方法名() {
    18. // 调用 actions 的方法
    19. this.$store.dispatch('方法名', 传值)
    20. }
    21. }
    22. }

    2)辅助函数

    1. import { mapState, ... } from 'vuex';
    2. export default {
    3. computed: {
    4. ...mapState(['数据名']), // 获取 state 数据
    5. ...mapGetters(['数据名']) // 获取 getters 数据
    6. },
    7. methods: {
    8. ...mapMutations(['方法名']), // 获取 mutations 方法
    9. ...mapActions(['方法名']), // 获取 actions 方法
    10. }
    11. }

    二、仓库模块

    1、仓库模块中设置数据和方法

    1. export default {
    2. namespaced: true,
    3. state: {},
    4. getters: {},
    5. mutations: {},
    6. actions: {}
    7. }
    模块创建好后,需要在主仓库中引入:
    1. import 模块 from './modules/模块.js'
    2. export default new Vuex.Store({
    3. state: {},
    4. getters: {},
    5. mutations: {},
    6. actions: {},
    7. modules: {
    8. 模块名: 模块
    9. }
    10. })

    2、组件中获取模块的数据和方法

    1)原生方式(不使用辅助函数)

    1. export default {
    2. computed: {
    3. 计算属性名() {
    4. // 获取指定模块中的 state 数据
    5. return this.$store.state.模块名.数据名;
    6. },
    7. 计算属性名() {
    8. // 获取指定模块中的 getters 数据
    9. return this.$store.getters['模块名/数据名'];
    10. }
    11. },
    12. methods: {
    13. 方法名() {
    14. // 调用指定模块的 mutations 的方法
    15. this.$store.commit('模块名/方法名', 传值)
    16. },
    17. 方法名() {
    18. // 调用指定模块的 actions 的方法
    19. this.$store.dispatch('模块名/方法名', 传值)
    20. }
    21. }
    22. }

    2)辅助函数

    1. import { createNamespacedHelpers } from 'vuex';
    2. const { mapState, mapActions } = createNamespacedHelpers('模块名');
    3. export default {
    4. computed: {
    5. ...mapState(['数据名']),
    6. ...mapGetters(['数据名'])
    7. },
    8. methods: {
    9. ...mapMutations(['方法名']),
    10. ...mapActions(['方法名']),
    11. }
    12. }
    如果我们在一个组件中,要通过辅助函数获取多个模块中的数据和方法时:
    1. import { createNamespacedHelpers } from 'vuex';
    2. const { mapState, mapActions } = createNamespacedHelpers('模块名一');
    3. const { mapState: 模块名二State, mapActions: 模块名二Actions } = createNamespacedHelpers('模块名二');