二、Vuex State

State 状态(共享的源数据)

Vuex 使用单一状态数: 用一个对象包含了全部的应用层级状态, 作为一个"唯一数据源"而存在.

在 Vue 组件中获得 Vuex 的状态

Vuex 中的状态存储是响应式的, 读取状态最简单的方法就是在计算属性中返回某个状态

const Child = {
    template: `<div>{{ count }}</div>`,
    computed: {
        count () {
            return this.$store.state.count
            // 当state.count变化时, 都会重新求取计算属性, 并触发更新相关联的 DOM
        }
    }
}

mapState 辅助函数

当一个组件需要获取多个状态时候, 将这些状态都声明为计算属性会有些重复. 可以使用 mapState 辅助函数生产计算属性, 减少单个声明的重复。

import { mapState } form 'vuex';

export default {
    computed: mapState({
        // 箭头函数可使代码更简练
        count: state => state.count,
        // 传字符串参数 'count' 等同于 state => state.count
        countAlias: 'count',
        // 为了能够使用 this 获取局部状态, 必须使用常规函数
        countPlusLocalState (state) {
            return state.count + this.localCount;
        }
    }),
    // 当映射的计算属性名称与state的节点名称相同时, 使用字符串数组
    computed: mapState([
        'count' 
        // 映射 this.count 为 this.$store.state.count
    ]),
    // 使用扩展运算符与局部计算属性混合使用
    computed: {
        localNum () { ... }, // 原有的计算属性
        // 将对象混入到外部对象中
        ...mapState({}),
        ...mapState(['count'])
    }
}
原文地址:https://www.cnblogs.com/yuxi2018/p/11966785.html