vuex 模块

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

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
}

导出为模块:vuex

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里定义的属性,其余都不能得到this

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中定义的方法的方法。spa

 

2017年1月9日更新:debug

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

//countryStore.js
export default {
    state:{
    },
    getters:{
    },
    actions:{ 
       /*//错误,无法使用命名空间
       getPage(context) {
       }  */
      
       //正确,在vue文件中能够使用 this.$store.dispatch("country/getPage") 便可
       ["country/getPage"](context) { }
    },
    mutations: {}
}
相关文章
相关标签/搜索