VueX模块的具体使用(小白教程)

2020-06-16 06:59:29易采站长站整理

}),
...mapGetters({
OnevaluePlus:'moduleOne/valuePlus',
TwovaluePlus:'moduleTwo/valuePlus',
OneglobalValue:'moduleOne/globalValuePlus',
TwoglobalValue:'moduleTwo/globalValuePlus',
OneotherValue:'moduleOne/otherValuePlus',
TwootherValue:'moduleTwo/otherValuePlus'
})
},
methods: {
...mapMutations(['moduleOne/updateValue','moduleTwo/updateValue']),
...mapActions(['moduleOne/timeOut'])
},
mounted() {
// this['moduleOne/updateValue']('我是改变后的值:1');
// this['moduleTwo/updateValue']('我是改变后的值:0');
this['moduleOne/timeOut']();
},
}
</script>

下面我们看下如何提交全局或者其他模块的

mutations


/* eslint-disable no-unused-vars */
import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

export default new Vuex.Store({
state:{
global:'this is global'
},
mutations:{
mode(state,data){
state.global=data
}
},
modules: {
moduleOne:{
namespaced:true,
state:{
moduleOnevalue:'1'
},
mutations:{
updateValue(state,value){
state.moduleOnevalue=value
}
},
getters:{
valuePlus(state){
return state.moduleOnevalue+'1'
},
globalValuePlus(state,getters,rootState){
return state.moduleOnevalue+rootState.global
},
otherValuePlus(state,getters,rootState){
return state.moduleOnevalue+rootState.moduleTwo.moduleTwovalue
},
},
actions:{
timeOut({state,commit,rootState}){
setTimeout(()=>{
commit('updateValue','我是异步改变的值:1')
},3000)
},
globaltimeOut({commit}){
setTimeout(()=>{
commit('mode','我改变了global的值',{root:true})
},3000)
}
}

},
moduleTwo:{
namespaced:true,
state:{
moduleTwovalue:'0'
},
mutations:{
updateValue(state,value){
state.moduleTwovalue=value
}
},
getters:{
valuePlus(state){
return state.moduleTwovalue+'0'
},
globalValuePlus(state,getters,rootState){
return state.moduleTwovalue+rootState.global
},
otherValuePlus(state,getters,rootState){
return state.moduleTwovalue+rootState.moduleOne.moduleOnevalue
},
}
}
}
})

页面引用。


<template>
<div class="home">
<p>moduleOne_state:{{moduleOne}}</p>
<p>moduleTwo_state:{{moduleTwo}}</p>