美文网首页
Vuex、modules

Vuex、modules

作者: 皇甫圣坤 | 来源:发表于2019-06-22 11:41 被阅读0次

模块

const store = new Vuex.Store({
  modules: {
    module名字: {
      // 每个模块都有自己独立state mutations actions getters 甚至还有modules
      state: {},
      getters: {},
      actions: {},
      mutations: {}
    }
  }
})

命名空间

我们可以给模块对象上添加namespaced: true

const store = new Vuex.Store({
  modules: {
    module名字: {
      namespaced: true
    }
  }
})

命名空间: 可以给我们的模块的getter mutation action上添加前缀 ‘模块名/’ 便于和其他模块以及root进行区分

state

模块中的state放在rootState下的模块名中 this.$store.state.模块名.属性名

const store = new Vuex.Store({
  modules: {
    module名字: {
      namespaced: true,
      state: {
        msg: '模块中的数据'
      }
    }
  }
})

// this.$store.state.module名字.msg namespaced属性对state没有任何影响

getters

所有模块的getter都放置在一起,为了区分,我们添加namespaced: true,这个时候,对应模块的getter就变成了 ‘模块名/getter名字’ 使用时
this.$store.getters['模块名/getter名字']

const store = new Vuex.Store({
  modules: {
    module名字: {
      namespaced: true,
      getters: {
        getter (state, getters, rootState) {
          // 只有在模块中的getter中才有第三个参数,
          //rootState可以只从其他模块获取数据 state指的是当前模块的state
        }
      }
    }
  }
})

mutations

所有模块的,mutation都放置在一起,为了区分,我们添加namespaced: true,这个时候,对应模块的,mutation就变成了 ‘模块名/,mutation名字’ 使用时 this.$store.commit('模块名/mutation名字')

如果是在action中使用

1.当前模块的action
commit('mutation名字')
2.其他模块的action
commit('模块名/mutation名字', null, {root: true})

actions

所有模块的,action都放置在一起,为了区分,我们添加namespaced: true,这个时候,对应模块的,action就变成了 ‘模块名/,action名字’ 使用时
this.$store.dispatch('模块名/action名字')

辅助函数写法

辅助函数写法
const store = new Vuex.Store({
  state: {
    a: 1
  },
  modules: {
    moduleA: {
      state: {
        b: 2,
        c: 3
      }
    }
  }
})


export default {
  computed: {
    ...mapState(['a', 'moduleA/b', 'moduleA/c']),
    ...mapState('moduleA', ['b', 'c'])
  }
}

相关文章

网友评论

      本文标题:Vuex、modules

      本文链接:https://www.haomeiwen.com/subject/xxvmqctx.html