最近找了个项目来练习,发现项目中有几处出现…mapState函数,遂去官网查看文档以及各路大佬分享的经验之谈,于是准备写点东西加深印象。
关于Vuex可前往官网查看更多内容,开始正文
mapState是state的辅助函数,其实也就是state的语法糖
1.不使用mapState
// store.js
Vue.use(Vuex);
export default new Vuex.Store({
state: {
count: 1,
},
mutations: {
increment(state) {
state.count += 1;
},
decrement(state) {
state.count -= 1;
},
},
在组件中调用vuex里state的内容
html
<template>
<!--index.vue-->
<div class="index">
<button @click="inCrement">increment</button>
count:{{count}}<br>
<button @click="deCrement">decrement</button>
</div>
</template>
js
computed: {
count() {
return this.$store.state.count; // 重点在这
},
},
methods: {
inCrement() {
this.$store.commit('increment'); // 提交Vuex中mutation的increment
},
deCrement() {
this.$store.commit('decrement'); // 提交Vuex中mutation的decrement
},
},
效果如下
- mapState
先在组件中引入
import { mapState } from 'vuex';
其他代码保持不变,computed中的要做修改
computed: mapState({
count: 'count', // 和上面的代码功能是一样的,但语法更简洁明了
}),
- …mapState
…是ES6中的扩展运算符,和上面的写法没多大差异,都是为了避免计算属性的重复和冗余
computed: {
...mapState({
count: 'count',
}),
},
后语:其他的mapGetters,mapMutations,mapActions和以上内容同理
参考来源:https://blog.youkuaiyun.com/dkr380205984/article/details/82185740