vuex是以插件的方式存在的。
安装:打开项目的根目录,即package.json所在目录,执行以下命令:
npm install vuex --save-dev
背景:小型应用里的每个组件维护着自有的状态,即当前应用的状态的一部分,所以整个应用的状态被分散在了各个角落,但是我们经常遇到要把 状态的一部分 共享给多个组件的情况。
状态其实可以形象地想成我们的 data 里面的各个属性。
一、Vuex
是一个专为 Vue.js 应用程序开发的状态管理模式。它采用集中式存储管理应用的所有组件的状态,并以相应的规则保证状态以一种可预测的方式发生变化。
这张图的重点:
-
数据流动是单向的
-
组件可以调用 actions
-
Actions 是用来分发 mutations 的
-
只有 mutations 可以修改状态
-
store 是反应式的,即,状态的变化会在组件内部得到反映
二、
有五个核心概念:State、Getters、Mutations、Actions、Modules。
Mutations
更改 Vuex 的 store 中的状态的唯一方法是提交 mutation。Vuex 中的 mutations 非常类似于事件:每个 mutation 都有一个字符串的 事件类型 (type) 和 一个 回调函数 (handler)。这个回调函数就是我们实际进行状态更改的地方,并且它会接受 state 作为第一个参数:
const store = new Vuex.Store({ state: { count: 1 }, mutations: { increment (state) { // 变更状态 state.count++ } } })
Action 类似于 mutation,不同在于:
- Action 提交的是 mutation,而不是直接变更状态。
- Action 可以包含任意异步操作。
待续。。
链接:http://vuex.vuejs.org/zh-cn/