(1).state/mutations/actions/getters各种写法解析
<template>
<div>
<div>{{index1}}</div>
<div>{{this.$store.state.index}}</div>
<div>{{showIndex}}</div>
<div>{{this.$store.getters.showIndex}}</div>
<button @click="updateIndex(1)">更改值</button>
<button @click="updateIndex1(2)">更改值1</button>
<button @click="updateIndex2">更改值2</button>
<button @click="aupdateIndex(1)">action更改值</button>
<button @click="aupdateIndex1(2)">action更改值1</button>
<button @click="aupdateIndex2">action更改值2</button>
</div>
</template>
<script>
import {mapState,mapMutations,mapGetters,mapActions} from 'vuex'
export default {
name:'index',
computed:{
//写法1
// ...mapState(['index'])
//写法2
...mapState({
index1:'index'
}),
//1.写法1
// ...mapGetters(['showIndex'])
...mapGetters({
showIndex:'showIndex'
})
},
methods:{
//写法1
...mapMutations(['updateIndex']),
//写法2
...mapMutations({
updateIndex1:'updateIndex',
}),
//写法3
updateIndex2(){
this.$store.commit('updateIndex',2)
},
//写法1
...mapActions(['aupdateIndex']),
//写法2
...mapActions({
aupdateIndex1:'aupdateIndex',
}),
//写法3
aupdateIndex2(){
this.$store.dispatch('aupdateIndex',2)
}
}
}
</script>
<style>
</style>
import Vue from 'vue';
import Vuex from 'vuex';
Vue.use(Vuex)
let store = new Vuex.Store({
state:{
index:0
},
mutations:{
updateIndex(state,value){
state.index = value
}
},
actions:{
aupdateIndex(ctx,index){
ctx.commit('updateIndex',index);
}
},
getters:{
showIndex(state){
return `我是你爹over${state.index}`
}
}
})
export default store;
(2).modules使用
store store1
let store = {
namespaced:true,
state:{
index:1
},
mutations:{
updateIndex(state,value){
state.index = value
}
},
}
export default store;
store store2
let store = {
namespaced:true,
state:{
index:2
},
mutations:{
updateIndex(state,value){
state.index = value
}
},
}
export default store;
store
import Vue from 'vue';
import Vuex from 'vuex';
Vue.use(Vuex)
import store1 from './store1'
import store2 from './store2'
let store = new Vuex.Store({
modules:{
store1,store2
}
})
export default store;
vue
<template>
<div>
<span>组件1:{{count1}}</span>
<span>组件2:{{count2}}</span>
<button @click="aupdateIndex1(3)">更改值1</button>
<button @click="aupdateIndex2(4)">更改值2</button>
</div>
</template>
<script>
import {mapState,mapMutations,mapGetters,mapActions} from 'vuex'
export default {
name:'index',
computed:{
//组件写法
...mapState('store1',{
count1: (state)=> state.index
}),
...mapState('store2',{
count2: (state)=> state.index
})
},
methods:{
...mapMutations('store1',{
aupdateIndex1:'updateIndex'
}),
...mapMutations('store2',{
aupdateIndex2:'updateIndex'
})
}
}
</script>
<style>
</style>