• Vuex 模块化 + 命名空间


    Vuex 模块化 + 命名空间

    1. 目的:让代码更好维护,让多种数据分类更加明确

    2. 修改 store.js (主模块)

      import Vue from 'vue'
      import Vuex from 'vuex'
      
      Vue.use(Vuex)
      const moduleA = {
          namespaced: true, // 开启命名空间
          state: { sum: 1 },
          actions: { ... },
          mutations: { ... },
          getter: {
              bigSum(state) {
                  return state.sum * 10
              }
          }
      };
                    
      const moduleB = {
      	namespaced: true,  // 开启命名空间
          state: { ... },
          actions: { ... },
          mutations: { ... },
          getter: {
              .....
          }            
      }
      // 引入子模块
      import moduleC from './module/moduleC'
      const store = new Vuex.Store({
       	modules: {
             moduleA, // 注册子模块
             moduleB,
             moduleC       
          }             
       })              
      
    3. 开启命名空间后,组件中读取state数据:

      // 方式一:自己直接读取
      this.$store.state.moduleA.xxx
      // 方式二:借助 mapState读取
      ...mapState('moduleA', ['xxx'])
      
    4. 开启命名空间后,组件中读取getter数据

      // 方式一:自己直接读取
      this.$store.getter['子模块/计算属性']
      // 方式二:借助 mapGetter读取
      ...mapGetter('子模块', ['计算属性'])
      
    5. 开启命名空间后,组件调用 dispatch

      // 方式一:自己直接dispatch
      this.$store.dispatch('子模块/子模块响应函数', 实参)
      // 方式二:借助 mapActions
      ...mapActions('子模块', { 生成的函数: '子模块actions中的函数'})
      
      
    6. 开启命名空间后,组件中调用commit

      // 方式一:自己直接commit
      this.$store.commit('子模块/子模块处理state的函数', 实参)
      // 方式二:借助mapMutations
      ...mapMutations('子模块', {生成的函数1: '子模块处理state的函数', 生成的函数2: '子模块处理state的函数'})
      

    总结

    • Vuex 将数据通过模块化的方式,拆分到多个子模块中进行管理,方便数据的管理
      • 主模块:只负责 数据子模块的 注册与挂载
      • 子模块:负责具体数据的状态管理
  • 相关阅读:
    thinkphp redis实现文章点赞功能并同步入mysql
    phpstorm2020.1最新版永久破解
    mysql修改sql_mode为宽松模式
    用为知发布博客到博客园、使用Wiz编写和发布博客园(cnblogs)博客
    Vim命令大全
    Vim教程
    GDB教程详解
    TCMalloc 对MYSQL 性能 优化的分析
    TCMalloc 安装和使用
    使用Tcmalloc进行堆栈分析
  • 原文地址:https://www.cnblogs.com/bingquan1/p/15876909.html
Copyright © 2020-2023  润新知