今天,在我編寫系統中一個模塊功能的時候,由於我使用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: {} }
