vuex 使用總結(詳解)
什麼情況下應該使用 Vuex?
Vuex 可以幫助我們管理共享狀態,並附帶了更多的概念和框架。這需要對短期和長期效益進行權衡。
如果您不打算開發大型單頁應用,使用 Vuex 可能是繁瑣冗餘的。確實是如此——如果您的應用夠簡單,您最好不要使用 Vuex。一個簡單的 store 模式 就足夠您所需了。但是,如果您需要構建一箇中大型單頁應用,您很可能會考慮如何更好地在元件外部管理狀態,Vuex 將會成為自然而然的選擇。
使用
在 Vue 的單頁面應用中使用,需要使用 Vue.use(Vuex)
呼叫外掛。將其注入到Vue根例項中。
import Vuex from 'vuex' Vue.use(Vuex) const store = new Vuex.Store({ state: { count: 0 }, getter: { doneTodos: (state, getters) => { return state.todos.filter(todo => todo.done) } }, mutations: { increment (state, payload) { state.count++ } }, actions: { addCount(context) { // 可以包含非同步操作 // context 是一個與 store 例項具有相同方法和屬性的 context 物件 } } }) // 注入到根例項 new Vue({ el: '#app', // 把 store 物件提供給 “store” 選項,這可以把 store 的例項注入所有的子元件 store, template: '<App/>', components: { App } })
然後改變狀態:
this.$store.commit('increment')
核心
State,Getter,Mutation,Action,Module,
Vuex 主要有四部分:
- state:包含了
store
中儲存的各個狀態。 - getter: 類似於 Vue 中的計算屬性,根據其他 getter 或 state 計算返回值。
- mutation: 一組方法,是改變
store
中狀態的執行者, 只能是同步操作 。 - action: 一組方法,其中可以 包含非同步操作 。
State
Vuex 使用 state
來儲存應用中需要共享的狀態。為了能讓 Vue 元件在 state
更改後也隨著更改,需要基於 state
建立計算屬性。
// 建立一個 Counter 元件 const Counter = { template: `<div>{{ count }}</div>`, computed: { count () { return this.$store.state.count// count 為某個狀態 } } }
Getter
類似於 Vue 中的 計算屬性(可以認為是 store 的計算屬性),getter 的返回值會根據它的依賴被快取起來,且只有當它的依賴值發生了改變才會被重新計算。
Getter 方法接受 state
作為其第一個引數:
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 方法也接受 state
和其他 getters
作為前兩個引數。
getters: { // ... doneTodosCount: (state, getters) => { return getters.doneTodos.length } }
store.getters.doneTodosCount // -> 1
我們可以很容易地在任何元件中使用它:
computed: { doneTodosCount () { return this.$store.getters.doneTodosCount } }
注意:getter 在通過屬性訪問時是作為 Vue 的響應式系統的一部分快取其中的。
通過方法訪問
也可以通過讓 getter 返回一個函式,來實現給 getter 傳參。在對 store 裡的陣列進行查詢時非常有用。
getters: { // ... getTodoById: (state) => (id) => { return state.todos.find(todo => todo.id === id) } }
store.getters.getTodoById(2) // -> { id: 2, text: '...', done: false }
注意:getter 在通過方法訪問時,每次都會去進行呼叫,而不會快取結果。
Mutation
mutations
才是改變狀態的執行者。
注意: mutations
只能是同步地更改狀態。
Vuex 中的 mutation 非常類似於事件:每個 mutation 都有一個字串的 事件型別 (type) 和 一個 回撥函式 (handler) 。這個回撥函式就是我們實際進行狀態更改的地方,並且它會接受 state 作為第一個引數:
const store = new Vuex.Store({ state: { count: 1 }, mutations: { increment (state) { // 變更狀態 state.count++ } } })
呼叫 store.commit
方法:
store.commit('increment')
提交載荷(Payload)
// ... mutations: { increment (state, n) { state.count += n } }
this.$store.commit('increment', 10)
其中,第一個引數是 state
,後面的引數是向 store.commit
傳入的額外的引數,即 mutation 的 載荷(payload) 。
store.commit
方法的第一個引數是要發起的 mutation
型別名稱,後面的引數均當做額外資料傳入 mutation
定義的方法中。
規範的發起 mutation
的方式如下:
// 以載荷形式 store.commit('increment',{ amount: 10//這是額外的引數 }) // 或者使用物件風格的提交方式 store.commit({ type: 'increment', amount: 10//這是額外的引數 })
額外的引數會封裝進一個物件,作為第二個引數傳入 mutation
定義的方法中。
mutations: { increment (state, payload) { state.count += payload.amount } }
Action
想要 非同步地更改狀態 ,就需要使用 action
。 action
並不直接改變 state
,而是發起 mutation
。
註冊一個簡單的 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。當我們在之後介紹到 Modules
時,你就知道 context 物件為什麼不是 store 例項本身了。
實踐中,我們會經常用到 ES2015 的 引數解構 來簡化程式碼(特別是我們需要呼叫 commit
很多次的時候):
actions: { increment ({ commit }) { commit('increment') } }
在action內部執行 非同步 操作:
actions: { incrementAsync ({ commit }) { setTimeout(() => { commit('increment') }, 1000) } }
發起 action
的方法形式和發起 mutation
一樣,只是換了個名字 dispatch
。
// 以物件形式分發Action store.dispatch({ type: 'incrementAsync', amount: 10 })
Actions 支援同樣的載荷方式和物件方式進行分發
Action處理非同步的正確使用方式
想要使用 action
處理非同步工作很簡單,只需要將非同步操作放到 action
中執行(如上面程式碼中的 setTimeout
)。
要想在非同步操作完成後繼續進行相應的流程操作,有兩種方式:
-
store.dispatch
返回相應action
的執行結果,而action的處理函式返回的就是Promise,所以store.dispatch
仍然返回一個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
進行組合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
在不同模組中可以觸發多個 action 函式。在這種情況下,只有當所有觸發函式完成後,返回的 Promise 才會執行。
Action與Mutation的區別
Action 類似於 mutation,不同在於:
- Action 提交的是 mutation,而不是直接變更狀態。
- Action 可以包含任意非同步操作,而Mutation只能且必須是同步操作。
Module
這時我們可以將 store 分割為 模組(module) ,每個模組擁有自己的 state
、 getters
、 mutations
、 actions
、甚至是巢狀子模組——從上至下進行同樣方式的分割。
程式碼示例:
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 的狀態
巢狀子模組
首先建立子模組的檔案:
// products.js // initial state const state = { added: [], checkoutStatus: null } // getters const getters = { checkoutStatus: state => state.checkoutStatus } // actions const actions = { checkout ({ commit, state }, products) { } } // mutations const mutations = { mutation1 (state, { id }) { } } export default { state, getters, actions, mutations }
然後在總模組中引入:
import Vuex from 'vuex' import products from './modules/products' //引入子模組 Vue.use(Vuex) export default new Vuex.Store({ modules: { products// 新增進模組中 } })
各個模組與 Vue 元件結合
將 state
和 getter
結合進元件需要使用 計算屬性 :
computed: { count () { return this.$store.state.count // 或者 return this.$store.getter.count } }
將 mutation
和 action
結合進元件需要在 methods
中呼叫 this.$store.commit()
或者 this.$store.commit()
:
methods: { changeDate () { this.$store.commit('change'); }, changeDateAsync () { this.$store.commit('changeAsync'); } }
為了簡便起見,Vuex 提供了四個輔助函式方法用來方便的將這些功能結合進元件。
mapState mapGetters mapMutations mapActions
示例程式碼:
import { mapState, mapGetters, mapMutations, mapActions } from 'vuex' export default { // ... computed: { localComputed () { /* ... */ }, // 使用物件展開運算子將此物件混入外部物件中 ...mapState({ // 為了能夠使用 `this` 獲取區域性狀態,必須使用常規函式 count(state) { return state.count + this.localCount } }), ...mapGetters({ getterCount(state, getters) { return state.count + this.localCount } }) } methods: { ...mapMutations({ // 如果想將一個屬性另取一個名字,使用以下形式。注意這是寫在物件中 add: 'increment' // 將 `this.add()` 對映為`this.$store.commit('increment')` }), ...mapActions({ add: 'increment' // 將 `this.add()` 對映為 `this.$store.dispatch('increment')` }) } }
如果結合進元件之後不想改變名字,可以直接使用 陣列 的方式。
methods: { ...mapActions([ 'increment', // 將 `this.increment()` 對映為 `this.$store.dispatch('increment')` // `mapActions` 也支援載荷: 'incrementBy' // 將 `this.incrementBy(amount)` 對映為 `this.$store.dispatch('incrementBy', amount)` ]), }
為何使用展開運算子: mapState
等四個函式返回的都是一個物件。我們如何將它與區域性計算屬性混合使用呢?通常,我們需要使用一個工具函式將多個物件合併為一個,以使我們可以將最終物件傳給 computed
屬性。但是有了 物件展開運算子 ,我們就可以進行簡化寫法。
Vuex的使用差不多就是這樣。還有名稱空間的概念,大型應用會使用。可以 點這裡檢視 。
附:專案結構
Vuex 不限制程式碼結構。但是規定了一些需要遵守的規則:
- 應用層級的狀態應該集中到單個 store 物件中。
- 提交 mutation 是更改狀態的唯一方法,並且這個過程是同步的。
- 非同步邏輯都應該封裝到 action 裡面。
只要你遵守以上規則,如何組織程式碼隨你便。如果 store 檔案太大,只需將 action、mutation 和 getter 分割到單獨的檔案。
對於大型應用,我們會希望把 Vuex 相關程式碼分割到模組中。下面是專案結構示例: