mapState辅助函数
作用:可以辅助获取到多个state的值
import Vuex from "vuex";
import Vue from "vue";
Vue.use(Vuex);
const state={
count:0,
num:100
}
const getters={
changeCount(){
return state.count++
}
}
const actions={
acCountAdd({commit},val){
commit('muCountAdd',val)
}
}
const mutations={
countAdd(state,val){
state.count+=val
}
}
export default new Vuex.Store({
state,
getters,
actions,
mutations
})
使用
<template>
<div>
<h2>home</h2>
<h3>vuex中的state的count:{{count}}</h3>
<h3>vuex中的getters的changeState:{{changeCount}}</h3>
<!-- 使用action辅助函数后,可以直接调用acCountAdd方法 -->
<button @click='acCountAdd(10)'>home改变vuex</button>
</div>
</template>
<script>
import {mapState, mapMutations, mapActions, mapGetters} from "vuex"
export default {
name: "Home",
computed:{
//
...mapState({
count: state=>state.count
}),
//
...mapGetters({
changeCount: 'changeCount'
})
},
methods: {
//
...mapMutations({
muCountAdd: 'muCountAdd'
}),
//
...mapActions({
acCountAdd: 'acCountAdd'
})
},
};
</script>
-
在.vue组件中引入
import { mapState } from 'vuex'
-
在vue组件中定义一个对象
computed:{ ...mapState({ count: state => state.count }) }
-
然后就可以不用$store.state.num引用了,直接插值
{{count}}
mapState需要写在computed中。
mapGetters、mapMutations、mapActions需要写在methos中。import { mapGetters} from 'vuex'
computed:{ ...mapGetters({ changeCount: 'changeCount' }) }