上一节我们是直接用 $store.state.count 来访问store状态的,现在我们是想处理一下,然后直接用 count 来调用:
第一种方法:用vue的computed计算属性,在Count.vue
<template>
<div>
<h1>{{ msg }}</h1>
<!--直接引用store里的数据-->
<h2>{{ $store.state.count }}--{{ count }}</h2>
<!--提交store里mutations内的方法-->
<button @click="$store.commit('add')">+</button>
<button @click="$store.commit('reduce')">-</button>
</div>
</template>
<script>
import store from '@/vuex/store'
export default {
data(){
return {
msg: 'Hello Vuex!'
}
},
computed:{
count(){
//注意要加this
return this.$store.state.count;
}
},
//将store添加到实例
store
}
</script>
<style>
</style>
第二种方法:通过vuex的mapState
<script>
import store from '@/vuex/store'
//注意mapState要加 {}
import { mapState } from 'vuex'
export default {
data(){
return {
msg: 'Hello Vuex!'
}
},
//同样是计算属性
computed:mapState({
//es6写法
count:state => state.count
}),
//将store添加到实例
store
}
</script>
其他和第一种一样
第三种:
<script>
import store from '@/vuex/store'
//注意mapState要加 {}
import { mapState } from 'vuex'
export default {
data(){
return {
msg: 'Hello Vuex!'
}
},
computed:mapState(['count']),
//将store添加到实例
store
}
</script>