iT邦幫忙

第 12 屆 iThome 鐵人賽

0
Modern Web

Vue菜鳥的自我學習days系列 第 31

31.Module

当应用变得非常复杂时,store 对象就有可能变得相当臃肿。
为了解决以上问题,Vuex 允许我们将 store 分割成 module。每个module拥有自己的 state、mutation、action、getter、甚至是嵌套子模块—(从上至下进行同样方式的分割)。

namespace:
默认情况下,module内部的 action、mutation 和 getter 是注册在namespace的',这样使得多个模块能够对同一 mutation 或 action 作出响应;如果希望module具有更高的封装度和复用性,你可以通过添加 namespaced: true 的方式使其成为带namespace的module。

const store = new Vuex.Store({
  modules: {
    account: {
      namespaced: true,

      // 模块内容(module assets)
      state: () => ({ ... }), // 模块内的状态已经是嵌套的了,使用 `namespaced` 属性不会对其产生影响
      getters: {
        isAdmin () { ... } // -> getters['account/isAdmin']
      },
      actions: {
        login () { ... } // -> dispatch('account/login')
      },
      mutations: {
        login () { ... } // -> commit('account/login')
      },

      // 嵌套模块
      modules: {
        // 继承父模块的命名空间
        myPage: {
          state: () => ({ ... }),
          getters: {
            profile () { ... } // -> getters['account/profile']
          }
        },

        // 进一步嵌套命名空间
        posts: {
          namespaced: true,

          state: () => ({ ... }),
          getters: {
            popular () { ... } // -> getters['account/posts/popular']
          }
        }
      }
    }
  }
})

上一篇
30.Action
下一篇
32.Module2
系列文
Vue菜鳥的自我學習days39
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言