State

单一状态树(存数据的)

存储在 Vuex 中的 State 和 Vue 实例中的 data 遵循相同的规则 使用场景分为全局引入和组件单独引入

// 如果store在main.js中全局注册了,那么在组件里可以这样用
this.$store.state;
// 如果全局没有注册,只是在组件里引入了store就得这样写
store.state;
// 当然也可以将单独引入得store挂到组件实例上,同样也可以用this去点出来,零活多用。
1
2
3
4
5

注意,这里得 state 就是咱们存在里面所以数据得集合,是一个对象。从本节开始,我们都默认为全局注册了得写法去记录
来一个完整得吧

// store.js
const store = new Vuex.Store({
  state: {
    count: 0
  },
  mutations: {
    increment (state) {
      state.count++
    }
  }
})
// main.js
import store from "./store";
new Vue({
  store,
  render: h => h(App)
}).$mount("#app");
// home.vue
<div>{{$store.state.count}}</div>
data() {
  return {
    num: this.$store.state.count
  }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24

辅助函数 mapState

当一个组件需要获取多个状态时候,将这些状态都声明为计算属性会有些重复和冗余。为了解决这个问题,我们可以使用 mapState 辅助函数帮助我们生成计算属性,让你少按几次键:

// 在单独构建的版本中辅助函数为 Vuex.mapState
import { mapState } from "vuex";

export default {
  // 计算属性里
  computed: mapState({
    // 箭头函数可使代码更简练
    count: (state) => state.count,

    // 【取别名】传字符串参数 'count' 等同于 `state => state.count`
    countAlias: "count",

    // 为了能够使用 `this` 获取局部状态,必须使用常规函数
    countPlusLocalState(state) {
      return state.count + this.localCount;
    },
  }),
};
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18

数组写法,直接拿值

当映射的计算属性的名称与 state 的子节点名称相同时,我们也可以给 mapState 传一个字符串数组。

computed: mapState([
  // 映射 this.count 为 store.state.count
  "count",
]);
1
2
3
4

对象展开运算符

很多情况下我们的计算属性里需要拥有自有的数据,那么就需要扩展开

computed: {
  localComputed () { /* 组件自身需要的属性 */ },
  // 使用对象展开运算符将此对象混入到外部对象中
  ...mapState({
    // ...
  })
}
1
2
3
4
5
6
7
Last Updated:
Contributors: websong