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

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

},
},
actions:{
timeOut({state,commit,rootState}){
setTimeout(()=>{
commit('updateValue','我是异步改变的值:1')
},3000)
},
globaltimeOut({commit}){
setTimeout(()=>{
commit('mode','我改变了global的值',{root:true})
},3000)
},
othertimeOut({commit}){
setTimeout(()=>{
commit('moduleTwo/updateValue','我改变了moduleTwo的值',{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>
<p>moduleOne_mapState:{{moduleOnevalue}}</p>
<p>moduleTwo_mapState:{{moduleTwovalue}}</p>
<p>moduleOne_mapGetters:{{OnevaluePlus}}</p>
<p>moduleTwo_mapGetters:{{TwovaluePlus}}</p>
<p>moduleOne_mapGetters_global:{{OneglobalValue}}</p>
<p>moduleTwo_mapGetters_global:{{TwoglobalValue}}</p>
<p>moduleOne_mapGetters_other:{{OneotherValue}}</p>
<p>moduleTwo_mapGetters_other:{{TwootherValue}}</p>
</div>
</template>
<script>
// eslint-disable-next-line no-unused-vars
import {mapState,mapMutations,mapGetters,mapActions} from 'vuex'
export default {
name:"Home",
data() {
return {
msg:"this is Home"
}
},
computed: {
moduleOne(){
return this.$store.state.moduleOne.moduleOnevalue
},
moduleTwo(){
return this.$store.state.moduleTwo.moduleTwovalue
},
...mapState({
moduleOnevalue:(state)=>state.moduleOne.moduleOnevalue,
moduleTwovalue:(state)=>state.moduleTwo.moduleTwovalue
}),
...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']),