Vuex的核心概念

Vuex有5個核心概念,分別是StateGettersmutationsActionsModules

State

  Vuex使用單一狀態樹,也就是說,用一個物件包含了所有應用層級的狀態,作為唯一資料來源而存在。沒一個Vuex應用的核心就是storestore可理解為儲存應用程式狀態的容器。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。當storecount發生改變時,元件內的計算屬性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選項更像是事件註冊,當觸發一個型別為incrementmutation時,呼叫此函式。要呼叫一個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 的響應規則

既然 Vuexstore 中的狀態是響應式的,那麼當我們變更狀態時,監視狀態的 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日誌,對於每個記錄的mutationdevtool都需要捕捉到前一狀態的快照。然而,在上面的例子中,mutation中的setTimeout方法中的回撥讓這不可能完成。因為當mutation被提交的時候,回撥函式還沒有被呼叫,devtool也無法知道回撥函式什麼時候真正被呼叫。實際上,任何在回撥函式中執行的狀態的改變都是不可追蹤的。

  如果確實需要執行非同步操作,那麼應該使用actionaction類似於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.statecontext.getters 來獲取 stategetters。甚至可以用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)。每個模組擁有自己的 statemutationactiongetter、甚至是巢狀子模組——從上至下進行同樣方式的分割:

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 的狀態

模組的區域性狀態

對於模組內部的 mutationgetter,接收的第一個引數是模組的區域性狀態物件。

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 檔案太大,只需將 actionmutationgetter 分割到單獨的檔案。

對於大型應用,我們會希望把 Vuex 相關程式碼分割到模組中。下面是專案結構示例:

└── store
├── index.js # 我們組裝模組並匯出 store 的地方
├── actions.js # 根級別的 action
├── mutations.js # 根級別的 mutation
└── modules
├── cart.js # 購物車模組
└── products.js # 產品模組