VueX 是一个专门为 Vue.js 应用设计的状态管理构架,统一管理和维护各个vue组件的可变化状态(你可以理解成 vue 组件里的某些 data )。
Vuex有五个核心概念:
state
,getters
,mutations
,actions
,modules
。
1. state:提供唯一的公共数据源,所有共享数据都要统一放到Store的State中进行存储
2. geeter:从基本数据(state)派生的数据,相当于state的计算属性
3. mutation:用于变更Store中的数据,必须是同步的(如果需要异步使用action)。每个 mutation 都有一个字符串的 事件类型 (type) 和 一个 回调函数 (handler)。
回调函数就是我们实际进行状态更改的地方,并且它会接受 state 作为第一个参数,提交载荷作为第二个参数,只能通过mutation变更store数据,不可以直接操作Store中的数据。
4. action:和mutation的功能大致相同,不同之处在于 1. Action 提交的是 mutation,而不是直接变更状态。 2. Action 可以包含任意异步操作。
5. modules:模块化vuex,可以让每一个模块拥有自己的state、mutation、action、getters,使得结构非常清晰,方便管理。
Vuex的用法:
- 安装 npm install vuex --save
- src里面创建store文件夹
- 创建index.js配置vuex
import Vue from "vue";
import Vuex from "vuex";
Vue.use(Vuex);
export default new Vuex.Store({
state: {
//存放的内容所有组件都可以访问,类似于data
name:"张三'
},
mutations: {},
actions: {},
modules: {},
});
- 在main.js
import store from "./store";
Vue.config.productionTip = false;
new Vue({
router,
store,
render: (h) => h(App),
}).$mount("#app");
核心概念:state、 getter 、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++
}
}
})
你不能直接调用一个 mutation 回调函数。要唤醒一个 mutation,你调用 store.commit 方法(参数为回调函数名):
store.commit('increment')
mutation回调函数的第一个参数始终为store,你能够向 store.commit 传入额外的参数,即 mutation 的 载荷(playload):
// ...
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
})
mutations对象风格的提交方式
提交 mutation 的另外一种方式是直接使用包含 type 属性的对象:
store.commit({
type: 'increment',
amount: 10
})
当使用对象风格的提交方式,整个对象都做为载荷传给 mutation 函数,所以 handler 保持不变:
mutations: {
increment (state, payload) {
state.count += payload.amount
}
}
你能够在组件中使用 this.$store.commit(‘xxx’) 提交 mutation,或者使用 mapMutations 辅助函数将组件中的 methods 映射为 store.commit 调用(须要在根节点注入 store)。
import { mapMutations } from 'vuex'
export default {
// ...
methods: {
...mapMutations([
'increment' // 映射 this.increment() 为 this.$store.commit('increment')
]),
...mapMutations({
add: 'increment' // 映射 this.add() 为 this.$store.commit('increment')
})
}
}
actions
action 相似于 mutation,不一样在于:
- action 提交的是 mutation,而不是直接变动状态。
- action 能够包含任意异步操做。
在 vuex
里面 actions
只是一个架构性的概念,并非必须的,本质上就是一个函数,你在里面想干吗均可以,能够经过异步方式执行各类任务,要修改state数据仍是须要经过commit触发 mutation 。
能够把mutation比做仓库的管理员,负责仓库管理,而把action比做领导,能够命令仓库管理员做操做,但不会亲自动手。
注册一个简单的 action:
const store = new Vuex.Store({
state: {
count: 0
},
mutations: {
increment (state) {
state.count++
}
},
actions: {
increment (context) {
context.commit('increment')
}
}
})
actions 的第一个参数是 context,它向外暴露一组与 store 实例相同的方法/属性,因此能够直接调用 context.commit 或者访问 context.state 或者 context.getters 。咱们一般使用 es6 的参数解构来简化咱们的代码,直接写成{ commit }
actions: {
increment ({ commit }) {
commit('increment')
}
}
Action 经过 store.dispatch 方法触发:
- store.dispatch(‘increment’)
乍一眼看上去感受画蛇添足,咱们直接分发 mutation 岂不更方便?实际上并不是如此,还记得 mutation 必须同步执行这个限制么?Action 就不受约束!咱们能够在 action 内部执行异步操做:
actions: {
incrementAsync ({ commit }) {
setTimeout(() => {
commit('increment')
}, 1000)
}
}
Actions 支持一样的载荷方式和对象方式进行分发:
- 以载荷形式分发
store.dispatch('incrementAsync', {
amount: 10
})
- 以对象形式分发
store.dispatch({
type: 'incrementAsync',
amount: 10
})
在组件中分发 Action
在组件中使用 this.$store.dispatch('xxx')
分发 action,或者使用 mapActions
辅助函数将组件的 methods 映射为 store.dispatch
调用(须要先在根节点注入 store
):
import { mapActions } from 'vuex'
export default {
// ...
methods: {
...mapActions([
'increment' // 映射 this.increment() 为 this.$store.dispatch('increment')
]),
...mapActions({
add: 'increment' // 映射 this.add() 为 this.$store.dispatch('increment')
})
}
}
组合 Actions
Action 一般是异步的,那么如何知道 action 何时结束呢?更重要的是,咱们如何才能组合多个 action,以处理更加复杂的异步流程?
第一件事你须要清楚的是 store.dispatch
的返回的是被触发的 action 函数的返回值,所以你能够在 action 中返回 Promise:
actions: {
actionA ({ commit }) {
return new Promise((resolve, reject) => {
setTimeout(() => {
commit('someMutation')
resolve()
}, 1000)
})
}
}
如今你能够:
store.dispatch('actionA').then(() => {
// ...
})
在另一个 action 中也能够:
actions: {
// ...
actionB ({ dispatch, commit }) {
return dispatch('actionA').then(() => {
commit('someOtherMutation')
})
}
}
最后,若是咱们利用 [async / await] 这个 JavaScript 即将到来的新特性,咱们能够像这样组合 action:
假设 getData() 和 getOtherData() 返回的是 Promise
actions: {
async actionA ({ commit }) {
commit('gotData', await getData())
},
async actionB ({ dispatch, commit }) {
await dispatch('actionA') // 等待 actionA 完成
commit('gotOtherData', await getOtherData())
}
}
Modules
使用单一状态树,致使应用的全部状态集中到一个很大的对象。可是,当应用变得很大时,store 对象会变得臃肿不堪。
为了解决以上问题,Vuex 运行咱们将 store 分割到多个模块(module)。每一个模块拥有本身的 state、mutation、action、getters、甚至是嵌套子模块——从上至下进行相似的分割:
const moduleA = {
state: { ... },
mutations: { ... },
actions: { ... },
getters: { ... }
}
onst moduleB = {
state: { ... },
mutations: { ... },
actions: { ... }
}
const store = new Vuex.Store({
modules: {
a: moduleA,
b: moduleB
}
})
store.state.a // -> moduleA 的状态
store.state.b // -> moduleB 的状态
模块的局部状态
对于模块内部的 mutation 和 getter,接收的第一个参数是模块的局部状态。
const moduleA = {
state: { count: 0 },
mutations: {
increment: (state) {
// state 模块的局部状态
state.count++
}
},
getters: {
doubleCount (state) {
return state.count * 2
}
}
}
一样,对于模块内部的 action,context.state
是局部状态,根节点的状态是 context.rootState
:
const moduleA = {
// ...
actions: {
incrementIfOdd ({ state, commit }) {
if (state.count % 2 === 1) {
commit('increment')
}
}
}
}
对于模块内部的 getter,根节点状态会做为第三个参数:
const moduleA = {
// ...
getters: {
sumWithRootCount (state, getters, rootState) {
return state.count + rootState.count
}
}
}