1.mapState
2.mapGetters
3.
4.
当你的操作行为中含有异步操作,比如向后台发送请求获取数据,就需要使用action的dispatch去完成。
其他使用commit即可。
举个例子:
const store = new Vuex.Store({
state: {
count: 10,
numb: 10086
},
getters: {
add: (state) => {
return state.count;
},
},
mutations: {
increment(state,val) {
if(val){
state.count += val;
}else{
state.count += 2;
} },
},
actions: {
actionA({dispatch, commit}) {
return commit('add');
},
increment({commit}) {
return commit('increment')
}
}
}); /* eslint-disable no-new */
new Vue({
router,
store,
render: h => h(App)
}).$mount('#app-box')
使用:
import {mapState,mapActions,mapMutations,mapGetters} from 'vuex'
methods:{
...mapMutations({addNumber:'increment'}),
increment(){
this.$store.dispatch('increment');
}
},
computed: {
...mapState({count:'numb'}),
...mapGetters(['add'])
},
<div class="hello">
<button @click="increment">加+2{{count}}</button>
</div>
<div class="hello">
<button @click="addNumber(5)">加+5{{count}}</button>
</div>
<div class="hello">
<button >{{add}}</button>
</div>
点击+2:store的count+=2
点击+5:store的count+=5
...mapState({count:'numb'}),
意思是this.count=this.$store.state.numb
...mapMutations({addNumber:'increment'}),
意思是之行this的addNumber函数的时候,执行this.$store的mutations的increment的函数