Vuex 是一个专为 Vue.js 应用程序开发的状态管理模式。它采用集中式存储管理应用的全部组件状态,并以相应的规则保证状态以一种可预测的方式发生变化。html
https://www.jianshu.com/p/5624362cd1f4--出处vue
看完这段专业的解释,我反正是一脸懵逼,心里毫无波澜,甚至有点想吃酱肘子。感受和没说同样嘛!keep going。es6
一个简单Vue计数器应用vuex
new Vue({ // state data () { return { count: 0 } }, // view template: ` <div>{{ count }}</div> `, // actions methods: { increment () { this.count++ } } })
这个状态自管理应用包含如下几个部分:api
这是一种“单向数据流”的理念。
而后说明一下这种理念的缺点,当咱们的应用遇到多个组件共享状态时,单向数据流的简洁性很容易被破坏:异步
- 多个视图依赖于同一状态。
- 来自不一样视图的行为须要变动同一状态。
这里说的是,vue 组件之间的传值操做,组件很少的状况下,嵌套的父子组件(prop,emit,on)和兄弟组件(global event bus)还容易操做一些。可是若是项目庞大,组件结构复杂,组件间的数据传递会变得很困难,后期代码不易维护。模块化
看到这里,貌似明白了些这鬼东西是要解决什么问题了。好的,而后咱们继续往“坑”里走。函数
每个 Vuex 应用的核心就是 store(仓库)。“store”基本上就是一个容器,它包含着你的应用中大部分的状态 (state)。Vuex 和单纯的全局对象有如下两点不一样:工具
// 若是在模块化构建系统中,请确保在开头调用了 Vue.use(Vuex) const store = new Vuex.Store({ state: { count: 0 }, mutations: { increment (state) { state.count++ } } })
如今,你能够经过 store.state 来获取状态对象,以及经过 store.commit 方法触发状态变动:this
store.commit('increment'); // 触发修改变量的方法 console.log(store.state.count); // -> 1
WTF?这是啥,这不就是“全局变量”嘛!多个组件可能用到的数据,存储到 store(仓库)里,可是这些数据是响应式的,因此对这些数据进行操做时,要遵照相应的规则。例如上面的例子。对 count 进行修改,要经过 commit 来触发 mutation 里的方法对数据进行操做。
让咱们开始吧。
Vuex 使用单一状态树,用一个对象就包含了所有的应用层级状态。至此它便做为一个“惟一数据源 (SSOT)”而存在。这也意味着,每一个应用将仅仅包含一个 store 实例。单一状态树让咱们可以直接地定位任一特定的状态片断,在调试的过程当中也能轻易地取得整个当前应用状态的快照。
这段话说的是一个 Vuex 只能包含一个store(存储数据的库),这样你在访问数据的时候好找些。
store 的其中一个配置项就是 state 。这个state吧,能够把他比做成vue实例中的data选项,就是把数据放在这里面。
const state = { // 商品列表 shopList:[{ id: 1, name: '兰博基尼', price: 10 },{ id: 2, name: '五菱宏光', price: 99999 }], // 购物车列表 addList: [] }; new Vuex.Store({ state, // 这里是es6语法,至关于 state: state ... });
获取商品列表 this.$store.state.shopList
就能看到了,或者使用辅助函数mapState,这样虽然方便简单,建议新手先研究一下 es6 和方法原理,这里不作解释。
computed: mapState([ // 映射 this.shopList为 store.state.shopList 'shopList' ])
Vuex 文档中有不少 es6 语法,若是有还不了解的同窗们,可要抓紧上车喽。
我一度怀疑是否是文档写错了,少加了一个s。(Getters)
这一项从字面意思上就能够看出,他是用来取数据,获得数据的。有人会问,为何不直接用this.$store.state.shopList
这种方式直接拿呢。这种方式确实能够拿到,可是常常会有一些状况是对拿到的数据作一些处理,例如格式化、过滤数据。。。这时候就会用到 Getter 了。
const getters = { // 获取id为2的商品 shopid2(state){ return state.shopList.find((el)=>{ return el.id == 2; }); } };
使用this.$store.getters.shopid2
获得五菱宏光,便可加入秋名山车神争霸,走上人生巅峰。
辅助函数 mapGetters 方法:
import { mapGetters } from 'vuex' export default { // ... computed: { // 使用对象展开运算符将 getter 混入 computed 对象中 ...mapGetters([ 'shopid2' // ... ]) } }
更改 Vuex 的 store 中的状态的惟一方法是提交 mutation。Vuex 中的 mutation 很是相似于事件:每一个 mutation 都有一个字符串的 事件类型 (type) 和 一个 回调函数 (handler)。这个回调函数就是咱们实际进行状态更改的地方,而且它会接受 state 做为第一个参数:
const store = new Vuex.Store({ state: { count: 1 }, mutations: { increment (state) { // 变动状态 state.count++ } } })
你须要以相应的 type 调用 store.commit 方法:this.$store.commit('increment')
你想要动个人数据,就得守我 Vuex 的规矩(顺我者昌,逆我者亡)。
拿数据用 Getters ,改数据用 mutation 。这个 mutation 有点像 vue 的生命周期钩子函数,里面是一些方法,经过 this.$store.commit(typeName)
对应的函数名称,触发对应的函数。
你能够向 store.commit 传入额外的参数,即 mutation 的 载荷(payload):
// ... mutations: { increment (state, n) { state.count += n } } store.commit('increment', 10); // 在大多数状况下,载荷应该是一个对象,这样能够包含多个字段而且记录的 mutation 会更易读 mutations: { increment (state, payload) { state.count += payload.amount } } store.commit('increment', { amount: 10 })
辅助函数 mapMutations 方法:
import { mapMutations } from 'vuex' export default { // ... methods: { ...mapMutations([ 'increment', // 将 `this.increment()` 映射为 `this.$store.commit('increment')` // `mapMutations` 也支持载荷: 'incrementBy' // 将 `this.incrementBy(amount)` 映射为 `this.$store.commit('incrementBy', amount)` ]), ...mapMutations({ add: 'increment' // 将 `this.add()` 映射为 `this.$store.commit('increment')` }) } }
在 Vuex 中,mutation 都是同步事务:
store.commit('increment') // 任何由 "increment" 致使的状态变动都应该在此刻完成。
为了处理异步操做,让咱们继续往下走 。
Action 相似于 mutation,不一样在于:
也就是说,Action 执行的仍是 Mutation ,只不过他能够异步执行,差很少就是给 Mutation 外边包了一层函数。
actions: { incrementAsync ({ commit }) { setTimeout(() => { commit('increment'); // 在异步函数成功后调用 Mutation }, 1000) } }
经过 this.$store.dispatch('incrementAsync')
便可调用。
辅助函数 mapActions 方法
import { mapActions } from 'vuex' export default { // ... methods: { ...mapActions([ 'increment', // 将 `this.increment()` 映射为 `this.$store.dispatch('increment')` // `mapActions` 也支持载荷: 'incrementBy' // 将 `this.incrementBy(amount)` 映射为 `this.$store.dispatch('incrementBy', amount)` ]), ...mapActions({ add: 'increment' // 将 `this.add()` 映射为 `this.$store.dispatch('increment')` }) } }
const moduleA = { state: { ... }, mutations: { ... }, actions: { ... }, getters: { ... } } const moduleB = { state: { ... }, mutations: { ... }, actions: { ... } } const store = new Vuex.Store({ modules: { a: moduleA, b: moduleB } }) store.state.a // -> moduleA 的状态 store.state.b // -> moduleB 的状态
├── index.html
├── main.js
├── api
│ └── ... # 抽取出API请求
├── components
│ ├── App.vue
│ └── ...
└── store
├── index.js # 咱们组装模块并导出 store 的地方
├── actions.js # 根级别的 action
├── mutations.js # 根级别的 mutation
└── modules
├── cart.js # 购物车模块
└── products.js # 产品模块
这个嘛,很简单。你以为你的项目里,各组件之间传参什么的,相处的很和谐,那就无所谓用不用了。
当你的组件兄弟们有传参问题,有不少这个组件要用,那个组件要,其余好几个组件也要,要的你生不如死,你就能够考虑一下了。
最后,咱们再回顾一下 Vuex 都包含什么,是作什么用的。
store
俗称仓库,仓库里是你的模块的数据、数据状态、对数据作的操做,都在这个仓库里。
state
仓库里的数据都放到这个里面,很像 vue 的 data 。
getters
一般获取能够用this.$store.state.shopList
就能够拿到,可是若是你想对这项数据加工一下(格式化、过滤),就在 getters 里处理,而后经过this.$store.getters.eventName
获取。
mutation
修改数据操做,你想对某项数据进行修改,就得守规矩。不能用this.$store.state.count=99
,要把修改函数写在 mutation 里面,用this.commit('eventName')
触发修改函数。注意,这里的操做必须是同步。
action
异步触发 mutation 。
module
给多个状态模块分类。