详讲vuex的辅助函数(映射函数)mapState,mapGetters,mapActions,mapMutations
作为一个使用vue框架的开发者,对vuex都不陌生,在这里就讲讲vuex的映射函数吧。
希望对感兴趣的人有一些帮助。然后给个关注或者赞支持下,一起分享。
html部分
<template>
<div class="demo1">
<div>没有使用mapState:{{$store.state.w1}}</div>
<div>使用mapState:{{w1}}</div>
<br>
<div>没有使用mapGetter:{{$store.getters.gbtn}}</div>
<div>使用mapGetter:{{gbtn}}</div>
<br>
<button @click="$store.dispatch('actionbtn',1)">没有使用mapAction:{{w2}}</button>
<br>
<button @click="actionbtn(1)">使用mapAction:{{w2}}</button>
<br>
<button @click="$store.commit('mutationbtn',1)">没有使用mapMutations:{{w3}}</button>
<br>
<button @click="mutationbtn(1)">使用mapMutations:{{w3}}</button>
<br>
</div>
</template>
<script>
import {mapState,mapGetters,mapActions,mapMutations} from "vuex"
export default {
name:"demo1",
components:{},
data(){
return {}
},
created(){},
methods:{
...mapMutations(['mutationbtn']),//将this.$store.action映射到methods
...mapActions(['actionbtn'])//同理
//如果觉得抽象,可以理解为,当通过click调methods的actionbtn方法=就相当于调actions的actionbtn方法
//actionbtn同理
},
mounted(){},
computed:{
...mapState(['w1','w2','w3']),
//是数组映射多个属性
//也可以是对象如 ...mapState({a:state.a,b:state.b})这种用法比较常见
...mapGetters(['gbtn'])
//mapGetter映射回的属性=调用getters里的方法的返回值,此属性可以当作data里的属性一样用
}
}
</script>
其实使用和不使用映射函数,除了写法上的区别,得到的值是一样的,也就是说使用了映射函数就等于从vue根实例上(this.$store)取值是一样的,但是在一般不推荐直接从根实例上取值。都是从state上取值,通过mutation修改值。随后会专门发博客讲为什么,以及vuex的工作流程。
*
JS部分*
const state = {
w1:1,
w2:2,
w3:3,
}
const actions = {
actionbtn({state,commit},payload){
state.w2=state.w2+payload
}
}
const mutations = {
mutationbtn(state,payload){
state.w3 = state.w3+payload
}
}
const getters = {
gbtn:state=>{
return state.w2
}
}
执行结果:
可以看到 用最传统的方法通过this.$store取值,和使用映射函数取的值是一样的,知道映射函数的好处了吧。
demo写的比较简单,希望有助于理解,注释分别都加了。由于时间问题,下次会把deom写的更通俗易懂。有问题和意见的可以加我好友一起分析分享。