辅助函数作用
为了简化vuex的使用,通常会使用到辅助函数,常用辅助函数有:
mapState、mapGetters、mapMutations、mapActions
mapState\mapGetters使用
当我们在模板中直接使用$store时,名称会过长,如果想用一个变量代替,可以使用计算属性
还有更优雅的方式,计算属性中利用辅助函数实现这个功能
<template>
<!-- <div>home页面 {{ $store.state.count }}</div> -->
<div>home页面 {{ count }}</div>
<!-- <div>计算属性:{{ $store.getters.doubleCount }}</div> -->
<div>计算属性:{{ doubleCount }}</div>
<div>
<button @click="add(5)">+5</button>
<br>
<button @click="delayAdd(10)">延迟+10</button>
</div>
</template>
<script>
import { mapState,mapGetters } from 'vuex'
export default {
name: 'HomeView',
computed: {
// count(){
// return this.$store.state.count
// },
// doubleCount(){
// return this.$store.getters.doubleCount
// }
// mapState\mapGetters函数会返回一个对象,因此需要用展开运算符
// 参数需要用state\getters中保存的属性名,必须用数组来作为参数,数组可以是多个属性名,同时获得多个state中保存的属性
...mapState(['count']),
...mapGetters(['doubleCount'])
},
data() {
return {
num: 11
}
},
methods: {
add(num) {
this.$store.commit('change', num)
},
delayAdd(num) {
this.$store.dispatch('asyncChange', num)
}
}
}
</script>
mapMutations\mapActions使用
这两个辅助函数需要在methods中使用