当前位置: 首页 > Web前端 > vue.js

vuex命名空间

时间:2023-03-31 18:32:06 vue.js

mapState,mapGetters,mapMutations,mapActions第一个参数是字符串(命名空间名称),第二个参数是数组(不需要重命名)/对象(需要重命名)。mapXXXs('namespacename',['propertyname1','propertyname2'])mapXXXs('namespacename',{  '组件中新名称1':'Vuex中原名称1',  'Newname2incomponent':'Originalname2inVuex',})项目结构mian.jsimportVuefrom"vue";importAppfrom"./App.vue";importrouterfrom"./router";importstorefrom"./store/index";Vue.config.productionTip=false;newVue({router,store,render:h=>h(App)}).$mount("#app");index.jsimportVuefrom"vue";importVuexfrom"vuex";importcatfrom"./modules/cat";importdogfrom"./modules/dog";Vue.use(Vuex);exportdefaultnewVuex.Store({modules:{cat,dog}});cat.jsexportdefault{namespaced:true,//局部状态state:{name:"bluewhiteEnglishshort",age:1},//局部读取getters:{desc:state=>"Pet:"+state.name},//局部变化mutations:{increment(state,payload){state.age+=payload.num;}},//本地动作actions:{grow(context,payload){setTimeout(()=>{context.commit("increment",payload);},1000);}}};dog.jsexportdefault{namespaced:true,//局部状态state:{name:"Labrador",age:1},//部分读取getters:{desc:state=>"Pet:"+state.name},//局部变化mutations:{increment(state,payload){state.age+=payload.num;}},//本地动作actions:{grow(context,payload){setTimeout(()=>{context.commit("increment",payload);},1000);}}};hello.vue运行效果