mapState 是用来简化 computed 计算属性的一种写法,下面做一个对比:
- 未使用之前
computed: {
count() {
return this.$store.state.count
}
},
- 使用mapState之后
computed: {
...Vuex.mapState([
'count'
]),
}
具体使用见下面代码详情
<!DOCTYPE html>
<html lang="en" xmlns="">
<head>
<meta charset="UTF-8">
<title>Vuex:mapState 的使用</title>
</head>
<body>
<div id="app">
<button-counter></button-counter>
</div>
<script src="vuex.js"></script>
<script src="vue.js"></script>
<script>
Vue.component('ButtonCounter', {
data() {
return {
localCount: 5
}
},
computed: {
...Vuex.mapState([
// 当映射的计算属性的名称与 state 的子节点名称相同时,我们也可以使用简写
// 与 count: state => state.count 作用相同
'count'
]),
...Vuex.mapState({
// 箭头函数可使代码更简练
count: state => state.count,
// 传字符串参数 'count' 等同于 `state => state.count`
countAlias: 'count',
// 为了能够使用 `this` 获取局部状态,必须使用常规函数
countPlusLocalState(state) {
return state.count + this.localCount
}
})
},
methods: {
...Vuex.mapMutations([
'increment'
]),
},
template: `
<div>
<button @click="increment">You clicked me {{ count }} times.</button>
<p>count: {{ count }}</p>
<p>countAlias: {{ countAlias }}</p>
<p>countPlusLocalState: {{ countPlusLocalState }}</p>
</div>
`
})
// 创建Vuex容器
const store = new Vuex.Store({
strict: true,
state: {
count: 0
},
mutations: {
increment(state) {
state.count++
}
}
})
new Vue({
el: '#app',
store
});
</script>
</body>
</html>