Vuex(三) state-状态对象的获取方法

1. 在组件的template中直接使用

    <h2>{{ $store.state.count }}</h2>

2. 在计算属性computed中直接赋值

// 方式1:直接获取
computed: {
    count() {
        // this指的是main.js中的vue实例对象
        return this.$store.state.count;
    }
}

3. 通过mapState的对象来赋值

// 方式2:利用mapState
computed: mapState({
    // es5写法
    count: function (state) {
         return state.count;
     },
    // es6写法
    count: state => state.count
})

4. 通过mapState的数组来赋值

// 方式3:数组获取
computed: mapState(['count'])

5. 通过mapState的JSON来赋值

// 方式4:JSON获取
computed: mapState({
    count: 'count'
})

一般4和5两种比较常用

6. 总结:完整示例代码

<template>
    <div class="hello">
        <h1>{{ msg }}</h1>
        <h2>{{ $store.state.count }}</h2>
        <h2>{{count}}</h2>
        <button @click="clickAdd">新增</button>
    </div>
</template>
<script>
import {mapState} from 'vuex'
export default {
    data () {
        return {
            msg: 'Vuex test!'
        }
    },
    // 方式1:在计算属性computed中直接赋值
    // computed: {
    //     count() {
    //         // this指的是main.js中的vue实例对象
    //         return this.$store.state.count;
    //     }
    // },
    // 方式2:通过mapState的对象来赋值
    // computed: mapState({
    //     // es5
    //     // count: function (state) {
    //     //     return state.count;
    //     // },
    //     // es6
    //     count: state => state.count
    // }),
    // 方式3:通过mapState的对象来赋值
    // computed: mapState(['count']),
    // 方式4:通过mapState的JSON来赋值
    computed: mapState({
        count: 'count'
    }),
    methods: {
        clickAdd() {
            //分发action中的add方法
            this.$store.dispatch('add', 1);
        }
    }
}
</script>
<style scoped>

</style>

 上一篇
Vuex(四) mutations-getters-actions异步 Vuex(四) mutations-getters-actions异步
更改 Vuex 的 store 中的状态的唯一方法是提交 mutation。Vuex 中的 mutation 非常类似于事件:每个 mutation 都有一个字符串的 事件类型 (type) 和 一个 回调函数 (handler)
2019-08-03
下一篇 
Vuex(二) 入门示例 Vuex(二) 入门示例
vuex是一个专为 Vue.js 应用程序开发的状态管理模式。它采用集中式存储管理应用的所有组件的状态,并以相应的规则保证状态以一种可预测的方式发生变化。
2019-07-31
  目录