2019-04-13 Vuex 模块

模块

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-persistedstate

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

推荐阅读更多精彩内容

  • State 单一状态树 Vuex使用单一状态树——用一个对象就包含了全部的应用层级状态。至此它便作为一个“唯一数据...
    oWSQo阅读 1,101评论 0 0
  • ### store 1. Vue 组件中获得 Vuex 状态 ```js //方式一 全局引入单例类 // 创建一...
    芸豆_6a86阅读 740评论 0 3
  • ### store 1. Vue 组件中获得 Vuex 状态 ```js //方式一 全局引入单例类 // 创建一...
    芸豆_6a86阅读 397评论 0 0
  • State 单一状态树 Vuex 使用单一状态树——是的,用一个对象就包含了全部的应用层级状态。至此它便作为一个“...
    peng凯阅读 710评论 2 0
  • Vuex是什么? Vuex 是一个专为 Vue.js应用程序开发的状态管理模式。它采用集中式存储管理应用的所有组件...
    萧玄辞阅读 3,153评论 0 6