vuex 模块

今天,在我编写系统中一个模块功能的时候,由于我使用vuex存储数据的状态,并分模块存储。我是这样在存储文件中定义state,getters,actions,mutations的,我打算在不同模块文件都使用相同的方法名称,然后在页面中带上模块名进行访问:

import * as types from '../mutation-types'

  const state = {    
  }
  const getters = {    
  }
  const actions = {
    /**
     * 获得一页数据
     */
    page(context) {     
    },
    /**
     * 获得一项信息
     */
    get(context) {
    },
    /**
     * 新增数据
     */
    create(context) {
    },
    /**
     * 更新数据
     */
    update(context) {
    },
    /**
     * 删除数据
     */
    delete(context) {
    }
  }
  const mutations = {   
  }

export default {
  state,
  getters,
  actions,
  mutations
}

导出为模块:

import country from "./modules/countryStore"

Vue.use(Vuex)

const debug = process.env.NODE_ENV !== 'production'

export default new Vuex.Store({
  actions,
  getters,
  modules: {
    country
  },
  //strict: debug,
  strict: false,  //不启用严格模式
})

然后我发现,在使用模块属性时,在页面里只能使用state里定义的属性,其他都不能获得

import { mapState,mapGetters, mapActions } from 'vuex'

  export default{
    computed:mapState({
        tableData: state => state.country.countryDataSet
     }),

    //不能获得  
    //mapGetters({
    //    tableData: (getters) => getters.country.countryDataSet
    //}),

    created(){
        this.$store.actions.country.page //.dispatch("country.page")
        //this.$store.dispatch("country.page")  //未找到
    },

这两种方法this.$store.dispatch("page")、this.$store.getters.countryDataSet(缺点是每个方法名都得是唯一的) 都是可以访问的,但是在一个大规范的应用中,应该存在不同模块中存在同名的方法,如:数据更新都使用update方法名,根据模块进行区分调用。这样开发起来也简单,代码也好理解。但是目前还没有找到使用模块来访问store中定义的方法的方法。

2017年1月9日更新:

实验过多种方式之后,下面这种方式可以在使用时加上方法前缀。

//countryStore.js
export default {
    state:{
    },
    getters:{
    },
    actions:{ 
       /*//错误,没法使用命名空间
       getPage(context) {
       }  */
      
       //正确,在vue文件中可以使用 this.$store.dispatch("country/getPage") 即可
       ["country/getPage"](context) {
       }
    },
    mutations: {}
}
原文地址:https://www.cnblogs.com/zuxiyo/p/6240574.html