# Vuex 文档初探(二): State

# 创建 store

import Vue from "vue";
import Vuex from "vuex";
Vue.use(Vuex);
const store = new Vuex.Store({
  state: {
    count: 0
  }
});
export default store;
1
2
3
4
5
6
7
8
9

# Getting Vuex State into Vue Components

  • 全局下使用 Vuex
import store from "store";
const Counter = {
  template: `<div>{{ count }}</div>`, // 0
  computed: {
    count() {
      return store.state.count;
    }
  }
};
1
2
3
4
5
6
7
8
9
  • 在组件里使用 Vuex
import store from "store";

const app = new Vue({
  el: "#app",
  // provide the store using the "store" option.
  // this will inject the store instance to all child components.
  store,
  components: { Counter },
  template: `
    <div class="app">
      <counter></counter>
    </div>
  `
});

const Counter = {
  template: `<div>{{ count }}</div>`,
  computed: {
    count() {
      return 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

# mapState

当一个组件内部多个状态需要多次使用到计算属性, 那么重复声明就显得啰嗦复杂. Vuex 提供 mapState 来解决这个问题:

// in full builds helpers are exposed as Vuex.mapState
import { mapState } from "vuex";

export default {
  // ...
  computed: mapState({
    // 直接返回count
    count: state => state.count,

    // passing the string value 'count' is same as `state => state.count`
    countAlias: "count",

    // to access local state with `this`, a normal function must be used
    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 tree 里一样, 我们可以直接在 mapState 里传入数组:

computed: mapState([
  // map this.count to store.state.count
  "count"
]);
1
2
3
4

# 对象展开符

当我们使用 mapState 时, 并不代表着全部的计算属性都是 store 里的, 我们还需要一些不用共享给其他组件的局部状态. 因此我们可以用对象展开符来解决:

computed: {
  localComputed () { /* ... */ },
  // mix this into the outer object with the object spread operator
  ...mapState({
    // ...
  })
}
1
2
3
4
5
6
7