Vuex的核心概念
Vuex有5個核心概念,分別是State,Getters,mutations,Actions,Modules。
State
Vuex使用單一狀態樹,也就是說,用一個對象包含了所有應用層級的狀態,作為唯一數據源而存在。沒一個Vuex應用的核心就是store,store可理解為保存應用程序狀態的容器。store與普通的全局對象的區別有以下兩點:
(1)Vuex的狀態存儲是響應式的。當Vue組件從store中檢索狀態的時候,如果store中的狀態發生變化,那么組件也會相應地得到高效更新。
(2)不能直接改變store中的狀態。改變store中的狀態的唯一途徑就是顯式地提交mutation。這可以確保每個狀態更改都留下可跟蹤的記錄,從而能夠啟用一些工具來幫助我們更好的理解應用
安裝好Vuex之后,就可以開始創建一個store,代碼如下:
const store = new Vuex.Store({
// 狀態數據放到state選項中
state: {
counter: 1000,
},
// mutations選項中定義修改狀態的方法
// 這些方法接收state作為第1個參數
mutations: {
increment(state) {
state.counter++;
},
},
});
在組件中訪問store的數據,可以直接使用store.state.count。在模塊化構建系統中,為了方便在各個單文件組件中訪問到store,應該在Vue根實例中使用store選項注冊store實例,該store實例會被注入根組件下的所偶遇子組件中,在子組件中就可以通過this.$store來訪問store。代碼如下:
new Vue({
el: "#app",
store,
})
如果在組件中要展示store中的狀態,應該使用計算屬性來返回store的狀態,代碼如下:
computed: {
count(){
return this.$store.state.count
}
}
之后在組件的模板中就可以直接使用count。當store中count發生改變時,組件內的計算屬性count也會同步發生改變。
那么如何更改store中的狀態呢?注意不要直接去修改count的值,例如:
methods: {
handleClick(){
this.&store.state.count++; // 不要這么做
}
}
既然選擇了Vuex作為你的應用的狀態管理方案,那么就應該遵照Vuex的要求;通過提交mutation來更改store中的狀態。在嚴格模式下,如果store中的狀態改變不是有mutation函數引起的,則會拋出錯誤,而且如果直接修改store中的狀態,Vue的調試工具也無法跟蹤狀態的改變。在開發階段,可以開啟嚴格模式,以避免字節的狀態修改,在創建store的時候,傳入strict: true代碼如下:
const store = new Vuex.Store({
strict: true
})
Vuex中的mutation非常類似於事件:每個mutation都有一個字符串的事件類型和一個處理器函數,這個處理器函數就是實際進行狀態更改的地方,它接收state作為第1個參數。
我們不能直接調用一個mutation處理器函數,mutations選項更像是事件注冊,當觸發一個類型為increment的mutation時,調用此函數。要調用一個mutation處理器函數,需要它的類型去調用store.commit方法,代碼如下:
store.commit("increment")
Getters
假如在store的狀態中定義了一個圖書數組,代碼如下:
export default new Vuex.Store({
state: {
books: [
{ id: 1, title: "Vue.js", isSold: false },
{ id: 2, title: "common.js", isSold: true },
{ id: 3, title: "node.js", isSold: true },
],
},
})
在組件內需要得到正在銷售的書,於是定義一個計算屬性sellingBooks,對state中的books進行過濾,代碼如下:
computed: {
sellingBooks(){
return this.$store.state.books.filter(book => book.isSold === true);
}
}
這沒有什么問題,但如果是多個組件都需要用到sellingBooks屬性,那么應該怎么辦呢?是復制代碼,還是抽取為共享函數在多處導入?顯然,這都不理想
Vuex允許我們在store中定義getters(可以認為是store的計算屬性)。與計算屬性一樣,getter的返回值會根據它的依賴項被緩存起來,且只有在它的依賴項發生改變時才會重新計算。
getter接收state作為其第1個參數,代碼如下:
export default new Vuex.Store({
state: {
books: [
{ id: 1, title: "Vue.js", isSold: false },
{ id: 2, title: "common.js", isSold: true },
{ id: 3, title: "node.js", isSold: true },
],
},
getters: {
sellingBooks(state) {
return state.books.filter((b) => b.isSold === true);
},
}
})
我們定義的getter將作為store.getters對象的豎向來訪問,代碼如下;
<h3>{{ $store.getters.sellingBooks }}</h3>
getter也可以接收其他getter作為第2個參數,代碼如下:
getters: {
sellingBooks(state) {
return state.books.filter((b) => b.isSold === true);
},
sellingBooksCount(state, getters) {
return getters.sellingBooks.length;
},
}
在組件內,要簡化getter的調用,同樣可以使用計算屬性,代碼如下:
computed: {
sellingBooks() {
return this.$store.getters.sellingBooks;
},
sellingBooksCount() {
return this.$store.getters.sellingBooksCount;
},
},
要注意,作為屬性訪問的getter作為Vue的響應式系統的一部分被緩存。
如果想簡化上述getter在計算屬性中的訪問形式,可以使用mapGetters輔助函數。mapGetters 輔助函數僅僅是將 store 中的 getter 映射到局部計算屬性:
import { mapGetters } from 'vuex'
export default {
// ...
computed: {
// 使用對象展開運算符將 getter 混入 computed 對象中
...mapGetters([
"sellingBooks",
"sellingBooksCount"
]),
}
}
如果你想將一個 getter 屬性另取一個名字,使用對象形式:
...mapGetters({
// 把 `this.booksCount` 映射為 `this.$store.getters.sellingBooksCount`
booksCount: 'sellingBooksCount'
})
getter還有更靈活的用法,用過讓getter返回一個函數,來實現給getter傳參。例如,下面的getter根據圖書ID來查找圖書對象
getters: {
getBookById(state) {
return function (id) {
return state.books.filter((book) => book.id === id);
};
},
}
如果你對箭頭函數已經掌握的爐火純青,那么可以使用箭頭函數來簡化上述代碼
getters: {
getBookById(state) {
return (id) => state.books.filter((book) => book.id === id);
},
下面在組件模板中的調用返回{ "id": 1, "title": "Vue.js", "isSold": false }
<h3>{{ $store.getters.getBookById(1) }}</h3>
mutation
上面已經介紹了更改store中的狀態的唯一方式是提交mutation。
提交載荷(Payload)
在使用store.commit方法提交mutation時,還可以傳入額外的參數,即mutation的載荷(payload),代碼如下:
mutations: {
increment(state, n) {
state.counter+= n;
},
},
store,commit("increment", 10)
載荷也可以是一個對象,代碼如下:
mutations: {
increment (state, payload) {
state.count += payload.amount
}
}
store.commit('increment', {
amount: 10
})
對象風格的提交方式
提交mutation時,也可以使用包含type屬性的對象,這樣傳一個參數就可以了。代碼如下所示:
store.commit({
type: "increment",
amount: 10
})
當使用對象風格提交時,整個對象將作為載荷還給mutation函數,因此處理器保持不變。代碼如下:
mutations: {
increment (state, payload) {
state.count += payload.amount
}
}
在組件中提交mutation時,使用的是this.$store.commit("increment"),如果你覺得這樣比較繁瑣,可以使用mapMutations輔助函數將組件中的方法映射為store.commit調用,代碼如下:
import { mapMutations } from "vuex";
methods: {
...mapMutations([
// 將this.increment()映射為this.$store.commit("increment")
"increment",
]),
}
除了使用字符串數組外,mapMutations函數的參數也可以是一個對象
import { mapMutations } from "vuex";
methods: {
...mapMutations([
// 將this.add()映射為this.$store.commit("increment")
add: "increment",
]),
}
Mutation 需遵守 Vue 的響應規則
既然 Vuex 的 store 中的狀態是響應式的,那么當我們變更狀態時,監視狀態的 Vue 組件也會自動更新。這也意味着 Vuex 中的 mutation 也需要與使用 Vue 一樣遵守一些注意事項:
1.最好提前在你的 store 中初始化好所有所需屬性。
2.當需要在對象上添加新屬性時,你應該
- 使用
Vue.set(obj, 'newProp', 123), 或者 - 以新對象替換老對象。例如,利用對象展開運算符 (opens new window)我們可以這樣寫:
state.obj = { ...state.obj, newProp: 123 }
使用常量替代 Mutation 事件類型
我們可以使用常量來替代mutation類型。可以把常量放到一個單獨的JS文件中,有助於項目團隊對store中所包含的mutation一目了然,例如:
// mutation-types.js
export const INCREMENT = "increment";
// store.js
import Vuex from "vuex";
import { INCREMENT } from "./mutation-types";
const store = new Vuex.Store({
state: { ... },
mutations: {
// 我們可以使用 ES2015 風格的計算屬性命名功能來使用一個常量作為函數名
[INCREMENT] (state) {
// mutate 狀態
}
}
})
Actions
在定義mutation時,有一個重要的原則就是mutation必須是同步函數,換句話說,在mutation處理器函數中,不能存在異步調用,比如
const store = new Vuex.Store({
state: {
count: 0
},
mutations: {
increment (state) {
setTimeout( () => {
state.count++
}, 2000)
}
}
})
在increment函數中調用setTimeout()方法在2s后更新count,這就是一個異步調用。記住,不要這么做,因為這會讓調試變得困難。假設正在調試應用程序並查看devtool中的mutation日志,對於每個記錄的mutation,devtool都需要捕捉到前一狀態的快照。然而,在上面的例子中,mutation中的setTimeout方法中的回調讓這不可能完成。因為當mutation被提交的時候,回調函數還沒有被調用,devtool也無法知道回調函數什么時候真正被調用。實際上,任何在回調函數中執行的狀態的改變都是不可追蹤的。
如果確實需要執行異步操作,那么應該使用action。action類似於mutation,不同之處在於:
action提交的是mutation,而不是直接變更狀態。action可以包含任意異步操作
一個簡單的action示例如下:
const store = new Vuex.Store({
state: {
count: 0
},
mutations: {
increment (state) {
state.count++
}
},
actions: {
increment(context) {
context.commit("increment");
},
},
})
Action 函數接受一個與 store 實例具有相同方法和屬性的 context 對象,因此你可以調用 context.commit 提交一個 mutation,或者通過 context.state 和 context.getters 來獲取 state 和 getters。甚至可以用context.dispatch調用其他的action。要注意的是,context對象並不是store實例本身
如果在action中需要多次調用commit,則可以考慮使用ECMAScript6中的解構語法來簡化代碼,如下所示:
actions: {
increment({ commit }) {
commit("increment");
},
},
action通過store.dispatch方法觸發,代碼如下:
actions: {
incrementAsync({ commit }) {
setTimeout(() => {
commit("increment");
}, 2000);
},
},
action同樣支持載荷和對象方式進行分發。代碼如下所示:
// 載荷是一個簡單的值
store.dispatch("incrementAsync", 10)
// 載荷是一個對象
store.dispatch("incrementAsync", {
amount: 10
})
// 直接傳遞一個對象進行分發
store.dispatch({
type: "incrementAsync",
amount: 10
})
在組件中可以使用this.$store.dispatch("xxx")分發action,或者使用mapActions輔助函數將組件的方法映射為store.dispatch調用,代碼如下:
// store.js
const store = new Vuex.Store({
state: {
count: 0
},
mutations: {
increment (state) {
state.count++
},
incrementBy(state, n){
state.count += n;
}
},
actions: {
increment({ commit }) {
commit("increment");
},
incrementBy({ commit }, n) {
commit("incrementBy", n);
},
},
})
// 組件
<template>
<div id="app">
<button @click="incrementNumber(10)">+10</button>
</div>
</template>
import { mapActions } from "vuex";
export default {
name: "App",
methods: {
...mapActions(["increment", "incrementBy"]),
};
action通常是異步的,那么如何知道action何時完成呢?更重要的是,我們如何才能組合多個action來處理更復雜的異步流程呢?
首先,要知道是store.dispatch可以處理被觸發的action的處理函數返回的Promise,並且store.dispatch仍舊返回Promise,例如:
actionA({ commit }) {
return new Promise((resolve, reject) => {
setTimeout(() => {
commit("increment");
resolve();
}, 1000);
});
},
現在可以:
store.dispatch("actionA").then(() => {
...
})
在另外一個action中也可以
actions: {
//...
actionB({dispatch, commit}) {
return dispatch("actionA").then(() => {
commit("someOtherMutation")
})
}
}
最后,如果我們利用 async / await (opens new window),我們可以如下組合 action:
// 假設 getData() 和 getOtherData() 返回的是 Promise
actions: {
async actionA ({ commit }) {
commit('gotData', await getData())
},
async actionB ({ dispatch, commit }) {
await dispatch('actionA') // 等待 actionA 完成
commit('gotOtherData', await getOtherData())
}
}
Module
由於使用單一狀態樹,應用的所有狀態會集中到一個比較大的對象。當應用變得非常復雜時,store 對象就有可能變得相當臃腫。
為了解決以上問題,Vuex 允許我們將 store 分割成模塊(module)。每個模塊擁有自己的 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 的狀態
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: {
incrementIfOddOnRootSum ({ state, commit, rootState }) {
if ((state.count + rootState.count) % 2 === 1) {
commit('increment')
}
}
}
}
對於模塊內部的 getter,根節點狀態會作為第三個參數暴露出來:
const moduleA = {
// ...
getters: {
sumWithRootCount (state, getters, rootState) {
return state.count + rootState.count
}
}
}
項目結構
Vuex 並不限制你的代碼結構。但是,它規定了一些需要遵守的規則:
1.應用層級的狀態應該集中到單個 store 對象中。
2.提交 mutation 是更改狀態的唯一方法,並且這個過程是同步的。
3.異步邏輯都應該封裝到 action 里面。
只要你遵守以上規則,如何組織代碼隨你便。如果你的 store 文件太大,只需將 action、mutation 和 getter 分割到單獨的文件。
對於大型應用,我們會希望把 Vuex 相關代碼分割到模塊中。下面是項目結構示例:
└── store
├── index.js # 我們組裝模塊並導出 store 的地方
├── actions.js # 根級別的 action
├── mutations.js # 根級別的 mutation
└── modules
├── cart.js # 購物車模塊
└── products.js # 產品模塊
