State
單一狀態(tài)樹
Vuex使用單一狀態(tài)樹——用一個對象就包含了全部的應用層級狀態(tài)。至此它便作為一個“唯一數(shù)據(jù)源”而存在。這也意味著,每個應用將僅僅包含一個store實例。單一狀態(tài)樹讓我們能夠直接地定位任一特定的狀態(tài)片段,在調(diào)試的過程中也能輕易地取得整個當前應用狀態(tài)的快照。
在Vue組件中獲得Vuex狀態(tài)
由于Vuex的狀態(tài)存儲是響應式的,從store實例中讀取狀態(tài)最簡單的方法就是在計算屬性中返回某個狀態(tài)。
// 創(chuàng)建一個 Counter 組件
const Counter = {
template: `<div>{{ count }}</div>`,
computed: {
count () {
return store.state.count
}
}
}
每當store.state.count變化的時候, 都會重新求取計算屬性,并且觸發(fā)更新相關聯(lián)的DOM。
然而,這種模式導致組件依賴全局狀態(tài)單例。在模塊化的構建系統(tǒng)中,在每個需要使用state的組件中需要頻繁地導入,并且在測試組件時需要模擬狀態(tài)。
Vuex通過store選項,提供了一種機制將狀態(tài)從根組件“注入”到每一個子組件中(需調(diào)用 Vue.use(Vuex))。
const app = new Vue({
el: '#app',
// 把 store 對象提供給 “store” 選項,這可以把 store 的實例注入所有的子組件
store,
components: { Counter },
template: `
<div class="app">
<counter></counter>
</div>
`
})
通過在根實例中注冊store選項,該store實例會注入到根組件下的所有子組件中,且子組件能通過this.$store訪問到。
const Counter = {
template: `<div>{{ count }}</div>`,
computed: {
count () {
return this.$store.state.count
}
}
}
mapState輔助函數(shù)
當一個組件需要獲取多個狀態(tài)時候,將這些狀態(tài)都聲明為計算屬性會有些重復和冗余。為了解決這個問題,我們可以使用mapState輔助函數(shù)幫助我們生成計算屬性。
// 在單獨構建的版本中輔助函數(shù)為 Vuex.mapState
import { mapState } from 'vuex'
export default {
// ...
computed: mapState({
// 箭頭函數(shù)可使代碼更簡練
count: state => state.count,
// 傳字符串參數(shù) 'count' 等同于 `state => state.count`
countAlias: 'count',
// 為了能夠使用 `this` 獲取局部狀態(tài),必須使用常規(guī)函數(shù)
countPlusLocalState (state) {
return state.count + this.localCount
}
})
}
當映射的計算屬性的名稱與state的子節(jié)點名稱相同時,我們也可以給mapState傳一個字符串數(shù)組。
computed: mapState([
// 映射 this.count 為 store.state.count
'count'
])
對象展開運算符
mapState函數(shù)返回的是一個對象。我們?nèi)绾螌⑺c局部計算屬性混合使用呢?通常,我們需要使用一個工具函數(shù)將多個對象合并為一個,以使我們可以將最終對象傳給computed屬性。但是自從有了對象展開運算符,我們可以極大地簡化寫法:
computed: {
localComputed () { /* ... */ },
// 使用對象展開運算符將此對象混入到外部對象中
...mapState({
// ...
})
}
Getter
有時候我們需要從store中的state中派生出一些狀態(tài),例如對列表進行過濾并計數(shù):
computed: {
doneTodosCount () {
return this.$store.state.todos.filter(todo => todo.done).length
}
}
如果有多個組件需要用到此屬性,我們要么復制這個函數(shù),或者抽取到一個共享函數(shù)然后在多處導入它——無論哪種方式都不是很理想。
Vuex允許我們在store中定義“getter”(可以認為是store的計算屬性)。就像計算屬性一樣,getter的返回值會根據(jù)它的依賴被緩存起來,且只有當它的依賴值發(fā)生了改變才會被重新計算。
Getter接受state作為其第一個參數(shù):
const store = new Vuex.Store({
state: {
todos: [
{ id: 1, text: '...', done: true },
{ id: 2, text: '...', done: false }
]
},
getters: {
doneTodos: state => {
return state.todos.filter(todo => todo.done)
}
}
})
通過屬性訪問
Getter會暴露為store.getters對象,你可以以屬性的形式訪問這些值:
store.getters.doneTodos // -> [{ id: 1, text: '...', done: true }]
Getter也可以接受其他getter作為第二個參數(shù):
getters: {
// ...
doneTodosCount: (state, getters) => {
return getters.doneTodos.length
}
}
store.getters.doneTodosCount // -> 1
我們可以很容易地在任何組件中使用它:
computed: {
doneTodosCount () {
return this.$store.getters.doneTodosCount
}
}
注意,getter在通過屬性訪問時是作為Vue的響應式系統(tǒng)的一部分緩存其中的。
通過方法訪問
你也可以通過讓getter返回一個函數(shù),來實現(xiàn)給getter傳參。在你對store里的數(shù)組進行查詢時非常有用。
getters: {
// ...
getTodoById: (state) => (id) => {
return state.todos.find(todo => todo.id === id)
}
}
store.getters.getTodoById(2) // -> { id: 2, text: '...', done: false }
注意,getter在通過方法訪問時,每次都會去進行調(diào)用,而不會緩存結果。
mapGetters輔助函數(shù)
mapGetters輔助函數(shù)僅僅是將store中的getter映射到局部計算屬性:
import { mapGetters } from 'vuex'
export default {
// ...
computed: {
// 使用對象展開運算符將 getter 混入 computed 對象中
...mapGetters([
'doneTodosCount',
'anotherGetter',
// ...
])
}
}
如果你想將一個getter屬性另取一個名字,使用對象形式:
mapGetters({
// 把 `this.doneCount` 映射為 `this.$store.getters.doneTodosCount`
doneCount: 'doneTodosCount'
})
Mutation
更改Vuex的store中的狀態(tài)的唯一方法是提交mutation。Vuex中的mutation非常類似于事件:每個mutation都有一個字符串的事件類型(type)和一個回調(diào)函數(shù) (handler)。這個回調(diào)函數(shù)就是我們實際進行狀態(tài)更改的地方,并且它會接受state作為第一個參數(shù):
const store = new Vuex.Store({
state: {
count: 1
},
mutations: {
increment (state) {
// 變更狀態(tài)
state.count++
}
}
})
你不能直接調(diào)用一個mutation handler。這個選項更像是事件注冊:“當觸發(fā)一個類型為increment的mutation時,調(diào)用此函數(shù)?!币獑拘岩粋€mutation handler,你需要以相應的type調(diào)用store.commit方法:
store.commit('increment')
提交載荷(Payload)
你可以向store.commit傳入額外的參數(shù),即mutation的載荷(payload):
mutations: {
increment (state, n) {
state.count += n
}
}
store.commit('increment', 10)
在大多數(shù)情況下,載荷應該是一個對象,這樣可以包含多個字段并且記錄的mutation會更易讀:
// ...
mutations: {
increment (state, payload) {
state.count += payload.amount
}
}
store.commit('increment', {
amount: 10
})
對象風格的提交方式
提交mutation的另一種方式是直接使用包含type屬性的對象:
store.commit({
type: 'increment',
amount: 10
})
當使用對象風格的提交方式,整個對象都作為載荷傳給mutation函數(shù),因此handler保持不變:
mutations: {
increment (state, payload) {
state.count += payload.amount
}
}
Mutation需遵守Vue的響應規(guī)則
既然Vuex的store中的狀態(tài)是響應式的,那么當我們變更狀態(tài)時,監(jiān)視狀態(tài)的Vue組件也會自動更新。這也意味著Vuex中的mutation也需要與使用Vue一樣遵守一些注意事項:
- 最好提前在你的
store中初始化好所有所需屬性。 - 當需要在對象上添加新屬性時,你應該使用
Vue.set(obj, 'newProp', 123), 或者以新對象替換老對象。例如,對象展開運算符我們可以這樣寫:
state.obj = { ...state.obj, newProp: 123 }
使用常量替代Mutation事件類型
使用常量替代mutation事件類型在各種Flux實現(xiàn)中是很常見的模式。這樣可以使linter之類的工具發(fā)揮作用,同時把這些常量放在單獨的文件中可以讓你的代碼合作者對整個 app包含的mutation一目了然:
// mutation-types.js
export const SOME_MUTATION = 'SOME_MUTATION'
// store.js
import Vuex from 'vuex'
import { SOME_MUTATION } from './mutation-types'
const store = new Vuex.Store({
state: { ... },
mutations: {
// 我們可以使用 ES2015 風格的計算屬性命名功能來使用一個常量作為函數(shù)名
[SOME_MUTATION] (state) {
// mutate state
}
}
})
Mutation必須是同步函數(shù)
一條重要的原則就是要記住mutation必須是同步函數(shù)。
mutations: {
someMutation (state) {
api.callAsyncMethod(() => {
state.count++
})
}
}
現(xiàn)在想象,我們正在debug一個app并且觀察devtool中的mutation日志。每一條mutation被記錄,devtools都需要捕捉到前一狀態(tài)和后一狀態(tài)的快照。然而,在上面的例子中mutation中的異步函數(shù)中的回調(diào)讓這不可能完成:因為當mutation觸發(fā)的時候,回調(diào)函數(shù)還沒有被調(diào)用,devtools不知道什么時候回調(diào)函數(shù)實際上被調(diào)用——實質(zhì)上任何在回調(diào)函數(shù)中進行的狀態(tài)的改變都是不可追蹤的。
在組件中提交Mutation
你可以在組件中使用this.$store.commit('xxx')提交mutation,或者使用mapMutations輔助函數(shù)將組件中的methods映射為store.commit調(diào)用(需要在根節(jié)點注入store)。
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')`
})
}
}
下一步:Action
在mutation中混合異步調(diào)用會導致你的程序很難調(diào)試。例如,當你調(diào)用了兩個包含異步回調(diào)的mutation來改變狀態(tài),你怎么知道什么時候回調(diào)和哪個先回調(diào)呢?這就是為什么我們要區(qū)分這兩個概念。在Vuex中,mutation都是同步事務:
store.commit('increment')
// 任何由 "increment" 導致的狀態(tài)變更都應該在此刻完成。
Action
Action類似于mutation,不同在于:
- Action提交的是
mutation,而不是直接變更狀態(tài)。 - Action可以包含任意異步操作。
讓我們來注冊一個簡單的 action:
const store = new Vuex.Store({
state: {
count: 0
},
mutations: {
increment (state) {
state.count++
}
},
actions: {
increment (context) {
context.commit('increment')
}
}
})
Action函數(shù)接受一個與store實例具有相同方法和屬性的context對象,因此你可以調(diào)用 context.commit 提交一個mutation,或者通過context.state和context.getters來獲取 state和getters。
實踐中,我們會經(jīng)常用到ES2015的參數(shù)解構來簡化代碼(特別是我們需要調(diào)用commit很多次的時候):
actions: {
increment ({ commit }) {
commit('increment')
}
}
分發(fā)Action
Action通過store.dispatch方法觸發(fā):
store.dispatch('increment')
乍一眼看上去感覺多此一舉,我們直接分發(fā)mutation豈不更方便?實際上并非如此,還記得mutation必須同步執(zhí)行這個限制么?Action就不受約束!我們可以在action內(nèi)部執(zhí)行異步操作:
actions: {
incrementAsync ({ commit }) {
setTimeout(() => {
commit('increment')
}, 1000)
}
}
Actions支持同樣的載荷方式和對象方式進行分發(fā):
// 以載荷形式分發(fā)
store.dispatch('incrementAsync', {
amount: 10
})
// 以對象形式分發(fā)
store.dispatch({
type: 'incrementAsync',
amount: 10
})
來看一個更加實際的購物車示例,涉及到調(diào)用異步API和分發(fā)多重mutation:
actions: {
checkout ({ commit, state }, products) {
// 把當前購物車的物品備份起來
const savedCartItems = [...state.cart.added]
// 發(fā)出結賬請求,然后樂觀地清空購物車
commit(types.CHECKOUT_REQUEST)
// 購物 API 接受一個成功回調(diào)和一個失敗回調(diào)
shop.buyProducts(
products,
// 成功操作
() => commit(types.CHECKOUT_SUCCESS),
// 失敗操作
() => commit(types.CHECKOUT_FAILURE, savedCartItems)
)
}
}
注意我們正在進行一系列的異步操作,并且通過提交mutation來記錄action產(chǎn)生的副作用(即狀態(tài)變更)。
在組件中分發(fā)Action
你在組件中使用this.$store.dispatch('xxx')分發(fā)action,或者使用mapActions輔助函數(shù)將組件的methods映射為store.dispatch 調(diào)用(需要先在根節(jié)點注入store):
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')`
})
}
}
組合Action
Action通常是異步的,那么如何知道action什么時候結束呢?更重要的是,我們?nèi)绾尾拍芙M合多個action,以處理更加復雜的異步流程?
首先,你需要明白store.dispatch可以處理被觸發(fā)的action的處理函數(shù)返回的Promise,并且store.dispatch仍舊返回Promise:
actions: {
actionA ({ commit }) {
return new Promise((resolve, reject) => {
setTimeout(() => {
commit('someMutation')
resolve()
}, 1000)
})
}
}
現(xiàn)在你可以:
store.dispatch('actionA').then(() => {
// ...
})
在另外一個action中也可以:
actions: {
// ...
actionB ({ dispatch, commit }) {
return dispatch('actionA').then(() => {
commit('someOtherMutation')
})
}
}
最后,如果我們利用async / await,我們可以如下組合action:
// 假設 getData() 和 getOtherData() 返回的是 Promise
actions: {
async actionA ({ commit }) {
commit('gotData', await getData())
},
async actionB ({ dispatch, commit }) {
await dispatch('actionA') // 等待 actionA 完成
commit('gotOtherData', await getOtherData())
}
}
一個
store.dispatch在不同模塊中可以觸發(fā)多個action函數(shù)。在這種情況下,只有當所有觸發(fā)函數(shù)完成后,返回的 Promise 才會執(zhí)行。
Module
由于使用單一狀態(tài)樹,應用的所有狀態(tài)會集中到一個比較大的對象。當應用變得非常復雜時,store對象就有可能變得相當臃腫。
為了解決以上問題,Vuex允許我們將store分割成模塊。每個模塊擁有自己的state、mutation、action、getter、甚至是嵌套子模塊——從上至下進行同樣方式的分割。
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 的狀態(tài)
store.state.b // -> moduleB 的狀態(tài)
模塊的局部狀態(tài)
對于模塊內(nèi)部的mutation和getter,接收的第一個參數(shù)是模塊的局部狀態(tài)對象。
const moduleA = {
state: { count: 0 },
mutations: {
increment (state) {
// 這里的 `state` 對象是模塊的局部狀態(tài)
state.count++
}
},
getters: {
doubleCount (state) {
return state.count * 2
}
}
}
同樣,對于模塊內(nèi)部的action,局部狀態(tài)通過context.state暴露出來,根節(jié)點狀態(tài)則為context.rootState。
const moduleA = {
// ...
actions: {
incrementIfOddOnRootSum ({ state, commit, rootState }) {
if ((state.count + rootState.count) % 2 === 1) {
commit('increment')
}
}
}
}
對于模塊內(nèi)部的getter,根節(jié)點狀態(tài)會作為第三個參數(shù)暴露出來。
const moduleA = {
// ...
getters: {
sumWithRootCount (state, getters, rootState) {
return state.count + rootState.count
}
}
}
命名空間
默認情況下,模塊內(nèi)部的action、mutation和getter是注冊在全局命名空間的——這樣使得多個模塊能夠對同一mutation或action作出響應。
如果希望你的模塊具有更高的封裝度和復用性,你可以通過添加namespaced: true 的方式使其成為帶命名空間的模塊。當模塊被注冊后,它的所有getter、action及mutation都會自動根據(jù)模塊注冊的路徑調(diào)整命名。例如:
const store = new Vuex.Store({
modules: {
account: {
namespaced: true,
// 模塊內(nèi)容(module assets)
state: { ... }, // 模塊內(nèi)的狀態(tài)已經(jīng)是嵌套的了,使用 `namespaced` 屬性不會對其產(chǎn)生影響
getters: {
isAdmin () { ... } // -> getters['account/isAdmin']
},
actions: {
login () { ... } // -> dispatch('account/login')
},
mutations: {
login () { ... } // -> commit('account/login')
},
// 嵌套模塊
modules: {
// 繼承父模塊的命名空間
myPage: {
state: { ... },
getters: {
profile () { ... } // -> getters['account/profile']
}
},
// 進一步嵌套命名空間
posts: {
namespaced: true,
state: { ... },
getters: {
popular () { ... } // -> getters['account/posts/popular']
}
}
}
}
}
})
啟用了命名空間的getter和action會收到局部化的getter,dispatch和commit。換言之,你在使用模塊內(nèi)容時不需要在同一模塊內(nèi)額外添加空間名前綴。更改namespaced屬性后不需要修改模塊內(nèi)的代碼。
在帶命名空間的模塊內(nèi)訪問全局內(nèi)容(Global Assets)
如果你希望使用全局state和getter,rootState和rootGetter會作為第三和第四參數(shù)傳入getter,也會通過context對象的屬性傳入action。
若需要在全局命名空間內(nèi)分發(fā)action或提交mutation,將{ root: true }作為第三參數(shù)傳給dispatch或commit即可。
modules: {
foo: {
namespaced: true,
getters: {
// 在這個模塊的 getter 中,`getters` 被局部化了
// 你可以使用 getter 的第四個參數(shù)來調(diào)用 `rootGetters`
someGetter (state, getters, rootState, rootGetters) {
getters.someOtherGetter // -> 'foo/someOtherGetter'
rootGetters.someOtherGetter // -> 'someOtherGetter'
},
someOtherGetter: state => { ... }
},
actions: {
// 在這個模塊中, dispatch 和 commit 也被局部化了
// 他們可以接受 `root` 屬性以訪問根 dispatch 或 commit
someAction ({ dispatch, commit, getters, rootGetters }) {
getters.someGetter // -> 'foo/someGetter'
rootGetters.someGetter // -> 'someGetter'
dispatch('someOtherAction') // -> 'foo/someOtherAction'
dispatch('someOtherAction', null, { root: true }) // -> 'someOtherAction'
commit('someMutation') // -> 'foo/someMutation'
commit('someMutation', null, { root: true }) // -> 'someMutation'
},
someOtherAction (ctx, payload) { ... }
}
}
}
在帶命名空間的模塊注冊全局action
若需要在帶命名空間的模塊注冊全局action,你可添加root: true,并將這個action的定義放在函數(shù)handler中。例如:
{
actions: {
someOtherAction ({dispatch}) {
dispatch('someAction')
}
},
modules: {
foo: {
namespaced: true,
actions: {
someAction: {
root: true,
handler (namespacedContext, payload) { ... } // -> 'someAction'
}
}
}
}
}
帶命名空間的綁定函數(shù)
當使用mapState, mapGetters, mapActions和mapMutations這些函數(shù)來綁定帶命名空間的模塊時,寫起來可能比較繁瑣:
computed: {
...mapState({
a: state => state.some.nested.module.a,
b: state => state.some.nested.module.b
})
},
methods: {
...mapActions([
'some/nested/module/foo', // -> this['some/nested/module/foo']()
'some/nested/module/bar' // -> this['some/nested/module/bar']()
])
}
對于這種情況,你可以將模塊的空間名稱字符串作為第一個參數(shù)傳遞給上述函數(shù),這樣所有綁定都會自動將該模塊作為上下文。于是上面的例子可以簡化為:
computed: {
...mapState('some/nested/module', {
a: state => state.a,
b: state => state.b
})
},
methods: {
...mapActions('some/nested/module', [
'foo', // -> this.foo()
'bar' // -> this.bar()
])
}
而且,你可以通過使用createNamespacedHelpers創(chuàng)建基于某個命名空間輔助函數(shù)。它返回一個對象,對象里有新的綁定在給定命名空間值上的組件綁定輔助函數(shù):
import { createNamespacedHelpers } from 'vuex'
const { mapState, mapActions } = createNamespacedHelpers('some/nested/module')
export default {
computed: {
// 在 `some/nested/module` 中查找
...mapState({
a: state => state.a,
b: state => state.b
})
},
methods: {
// 在 `some/nested/module` 中查找
...mapActions([
'foo',
'bar'
])
}
}
模塊動態(tài)注冊
在store創(chuàng)建之后,你可以使用store.registerModule方法注冊模塊。
// 注冊模塊 `myModule`
store.registerModule('myModule', {
// ...
})
// 注冊嵌套模塊 `nested/myModule`
store.registerModule(['nested', 'myModule'], {
// ...
})
之后就可以通過store.state.myModule和store.state.nested.myModule訪問模塊的狀態(tài)。
模塊動態(tài)注冊功能使得其他Vue插件可以通過在store中附加新模塊的方式來使用Vuex管理狀態(tài)。例如,vuex-router-sync插件就是通過動態(tài)注冊模塊將vue-router和vuex結合在一起,實現(xiàn)應用的路由狀態(tài)管理。
你也可以使用store.unregisterModule(moduleName)來動態(tài)卸載模塊。注意,你不能使用此方法卸載靜態(tài)模塊(即創(chuàng)建store時聲明的模塊)。
在注冊一個新module時,你很有可能想保留過去的state,例如從一個服務端渲染的應用保留 state。你可以通過preserveState選項將其歸檔:store.registerModule('a', module, { preserveState: true })。
模塊重用
有時我們可能需要創(chuàng)建一個模塊的多個實例,例如:
- 創(chuàng)建多個
store,他們公用同一個模塊 (例如當runInNewContext選項是false或'once'時,為了在服務端渲染中避免有狀態(tài)的單例) - 在一個
store中多次注冊同一個模塊
如果我們使用一個純對象來聲明模塊的狀態(tài),那么這個狀態(tài)對象會通過引用被共享,導致狀態(tài)對象被修改時store或模塊間數(shù)據(jù)互相污染的問題。
實際上這和Vue組件內(nèi)的data是同樣的問題。因此解決辦法也是相同的——使用一個函數(shù)來聲明模塊狀態(tài)(僅 2.3.0+ 支持):
const MyReusableModule = {
state () {
return {
foo: 'bar'
}
},
// mutation, action 和 getter 等等...
}