Vuex 的 Module 用法 --vue-admin-element

Vuex 的 Module 用法 --vue-admin-element

module 大体写法如下

const moduleA = {
  state: { ... },
  mutations: { ... },
  actions: { ... },
  getters: { ... }
}

const moduleB = {
  state: { ... },
  mutations: { ... },
  actions: { ... }
}

const store = new Vuex.Store({
  modules: {
    a: moduleA,
    b: moduleB
  }
})

module 写法还可以分成多个文件夹 利用 node fs模块 快速导入
单个module 里面的功能大有讲究

const moduleA = {
  namespaced:true, //讲究
  state: { count: 0 },
  mutations: {
    increment (state) {  //state 讲究
      // 这里的 `state` 对象是模块的局部状态
      state.count++
    }
  },

  getters: {
    doubleCount (state) {
      return state.count * 2
    }
  },
  actions: {
        incrementIfOddOnRootSum ({ state, commit, getters,rootState,rootGetters , }) {  //参数讲究
        root:true          //讲究
        getters.someGetter // -> 'foo/someGetter'
        rootGetters.someGetter // -> 'someGetter'

        dispatch('someOtherAction') // -> 'foo/someOtherAction'
        dispatch('someOtherAction', null, { root: true }) // -> 'someOtherAction'

        commit('someMutation') // -> 'foo/someMutation'
        commit('someMutation', null, { root: true }) // -> 'someMutation'
    }
  }
}

1 namespaced:true 让每个module 独立化
2 state 默认调用的是当前module 的内容
3 rootState 调用根路径的state 或者 再利用它调用别的module 的内容
4 root:true 成为根路径的方法 // 用法:类似java的static 逻辑上脱离module
5 getters commit dispatch 都被局部化 commit 和dispatch 传参 第一个方法名,第二个参数,第三个{root:true} ? 设置了等于调用root下的方法

**

module化下: mapState, mapGetters, mapActions 和 mapMutations 的写法

未优化前

computed: {
  ...mapState({
    a: state => state.some.nested.module.a,
    b: state => state.some.nested.module.b
  })
},
methods: {
  ...mapActions([
    'some/nested/module/foo', // -> this['some/nested/module/foo']()
    'some/nested/module/bar' // -> this['some/nested/module/bar']()
  ])
}

优化 1
动态...

computed: {
  ...mapState('some/nested/module', {
    a: state => state.a,
    b: state => state.b
  })
},
// 另外也可以如下
computed: {
  ...mapState('some/nested/module', [a,b]);
}

优化 2
静态..

const { mapState, mapActions } = createNamespacedHelpers('some/nested/module')

export default {
  computed: {
    // 在 `some/nested/module` 中查找
    ...mapState({
      a: state => state.a,
      b: state => state.b
    })
  },
  methods: {
    // 在 `some/nested/module` 中查找
    ...mapState([
      'a',
      'b'
    ])
  

上面只有用mapState 演示..其他不列举
vuex的基本用法链接 https://www.jianshu.com/p/b7667f2f5b5b

升级至插件开发者参考官网 https://vuex.vuejs.org/zh/guide/strict.html
https://vuex.vuejs.org/zh/api/#vuex-store

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。