File tree Expand file tree Collapse file tree 1 file changed +52
-1
lines changed
Expand file tree Collapse file tree 1 file changed +52
-1
lines changed Original file line number Diff line number Diff line change 1- # Quickstart
1+ # 快速开始
22
3+ 每一个基于 Vuex 的应用的核心就是 ** store** . "store" 基本上就是一个装有你的应用的大部分 ** 状态** (即 ** state** )的容器. Vuex 和普通的全局对象有以下两点不同:
4+
5+ 1 . Vuex 的状态存储是动态的. 当 Vue 组件从 store 中的 state 读取状态的时候, 如果 store 中的 state 改变,那么响应的组件也会动态并高效的改变.
6+
7+ 2 . 你不能直接改变 store 中的 state. 改变 store 中的 state 的唯一途径就是明确的 dispatch ** mutations** 事件. 这样使得每一个状态的变化冻很容易追踪, 并且能够让我们通过工具更了解应用内部的状态.
8+
9+ ### 最简单的 store
10+
11+ > ** 注意:** 在接下来的文档中,我们将会在后面的例子中使用 ES2015 的语法。如果你还没能掌握 ES2015,[ 你应该这样] ( https://babeljs.io/docs/learn-es2015/ ) ! 文档同样也认为你已经熟悉了 [ Building Large-Scale Apps with Vue.js] ( http://vuejs.org/guide/application.html ) 中所涉及的概念.
12+
13+ 创建 Vuex 的 store 相当直截了当 - 只要提供一个初始化的 state 对象,以及一些 mutations:
14+
15+ ``` js
16+ import Vuex from ' vuex'
17+
18+ const state = {
19+ count: 0
20+ }
21+
22+ const mutations = {
23+ INCREMENT (state ) {
24+ state .count ++
25+ }
26+ }
27+
28+ const store = new Vuex.Store ({
29+ state,
30+ mutations
31+ })
32+ ```
33+
34+ 现在,你可以通过 ` store.state ` 来读取状态对象,还可以通过 dispatch mutation 的名字来触发改变:
35+
36+ ``` js
37+ store .dispatch (' INCREMENT' )
38+
39+ console .log (store .state .count ) // -> 1
40+ ```
41+
42+ 如果你更喜欢对象风格的 dispatch,你也可以这么做:
43+
44+ ``` js
45+ // 同上例效果
46+ store .dispatch ({
47+ type: ' INCREMENT'
48+ })
49+ ```
50+
51+ 再次强调,我们通过 dispatch 一个 mutation 而不是直接改变 ` store.state.count ` ,是因为我们想要明确追踪状态的变化。这个简单的约定,能够让你不会状态混乱,这让应用状态改变的时候,在代码中能够更好的定位。此外,这样也给了我们机会通过工具来记录每次状态改变、状态快照、甚至像时间旅行一样调试。
52+
53+ 这里只是一个最简单的理解展示 store 的状态存储。但是 Vuex 不仅仅是状态存储。接下来,我们将会深入探讨一些核心概念:[ State] ( state.md ) , [ Mutations] ( mutations.md ) 和 [ Actions] ( actions.md ) .
You can’t perform that action at this time.
0 commit comments