vuex的模块

<script>
    /* 
    
      模块中的state会变成rootState的一个属性,属性名为模块名

      模块中的state
        rootState
          this.$store.state.msg
        moduleA state
          this.$store.moduleA.msg
        moduleB state
          this.$store.moduleB.msg

      模块中的getters
        模块中的getter和rootGetter会放在同一个对象中
          this.$store.getters 所以尽量不要其相同名字
      
    
     */
</script>
<script>
    /* 
      为什么会有命名空间
        因为getter添加不管是哪个模块的,都会直接被添加到
        this.$store.getters中,如果两个名字相同,所以需要添加
          namespaced: true

          对应模块的getter就会变成"模块名/getter名"

      模块中的getter里的第一个参数指向的是当前模块的state
      modules: {
        moduleA: {
          getters: {
            getter名字 (state, getters, rootState,rootGetters) {
              // state和getters都指当前模块的内容
              // rootState指全局中的state包含了各个模块的state

            }
          }
        }
      }

      除了getter名字会变成 mudule名/getter名 外

      mutation和action也会变成
      module名/mutation名字
      module名/action名字

      建议模块添加namespaced属性
    */

<script>
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Document</title>
</head>
<body>
  <!-- 
    state不会有任何变化
      rootState
        this.$store.state.xxx
      模块state
        this.$store.state.模块名.xxx

    getters添加了namespaced之后 会给对应的getter添加模块名变成 "模块名/getter名字" 全局的getter不会有任何变化
    想要获取到对应的getter
    this.$store.getters['模块名字/getter名字']

    模块的getter (state, getters, rootState, rootGetters) {
      // state getters表示当前模块的state和getters
      // rootState rootGetters表示全局中的state和getters

    }


    mutations和getters相同,添加namespaced之后会给对应的mutation添加模块名 变成 "模块名/mutation名字"

    commit('模块名/mutation名字', 数据)

    模块中的mutation (state, 载荷) {
      // 没有变化
    }

    actions同上,添加了namespaced属性后,会给对应的action添加模块名变成 "模块名/action名字"

    dispatch('模块名/action名字', 数据)

    模块中的action ({commit}, 数据) {
      // 模块中的action里的commit只能提交当前模块中的mutation
      
    }
  若需要在带命名空间的模块注册全局 action,你可添加 root: true
  可以访问到全局的
  当前模块的变成 '模块名/action名字'
--> </body> </html>

 

posted @ 2018-12-30 14:51  宝2333  阅读(250)  评论(0编辑  收藏  举报