上一节我们是直接用 $store.state.count 来访问 store 状态的,现在我们是想处理一下,然后直接用 count 来调用:
第一种方法:用 vue 的 computed 计算属性,在 Count.vue
- <template>
- <p>
- <h1>{{ msg }}</h1>
- <!--直接引用store里的数据-->
- <h2>{{ $store.state.count }}--{{ count }}</h2>
- <!--提交store里mutations内的方法-->
- <button @click="$store.commit('add')">+</button>
- <button @click="$store.commit('reduce')">-</button>
- </p>
- </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>
来源: https://www.2cto.com/kf/201801/709558.html