1、什麼是vuex?
Vuex 是一個專為 Vue.js 應用程式開發的狀态管理模式。它采用集中式存儲管理應用的所有元件的狀态,并以相應的規則保證狀态以一種可預測的方式發生變化,進而到達各個元件之間的資料共享!
什麼情況下我應該使用 Vuex?
引用 Redux 的作者 Dan Abramov 的話說就是:
Flux 架構就像眼鏡:您自會知道什麼時候需要它。
當我們的項目越來越複雜時,多個視圖可能公用一個狀态,并且不同視圖需要變更同一個狀态時,我們就發現傳參的方法對于多層嵌套的元件将會非常繁瑣,并且對于兄弟元件間的狀态傳遞無能為力,并且簡單的store存儲已經不能滿足我們的需求,維護起來也比較困難。是以當我們考慮如何在元件外部更好的管理狀态時,就是我們需要vuex的時候了。
了解狀态管理的核心概念
state
單一狀态樹,用一個對象就包含了全部的應用層級狀态,如下所示,state對象中存儲的我們需要的是一個一個的狀态。
state: {
state1: '狀态1',
state2: {
name: 狀态2,
id: 2
}
}
如何擷取state
- 從store中擷取state : this.$store.state.count
Vuex 通過
store
選項,提供了一種機制将狀态從根元件“注入”到每一個子元件中(需調用
Vue.use(Vuex)
),且子元件能通過
this.$store
可以通路到。
const app = new Vue({
el: '#app',
// 把 store 對象提供給 “store” 選項,這可以把 store 的執行個體注入所有的子元件
store,
components: { Counter },
template: `
<div class="app">
<counter></counter>
</div>
`
})
- 從
mapState中擷取
當一個元件需要擷取多個狀态時候,将這些狀态都聲明為計算屬性會有些重複和備援。因為每一個計算屬性都是一個函數,并且需要我們每個都寫return this.$store.state不是很友善。為了解決這個問題,我們可以使用
mapState
輔助函數幫助我們生成計算屬性。它的兩種用法,或接受一個對象,或接受一個數組
// 在單獨建構的版本中輔助函數為 Vuex.mapState
import { mapState } from 'vuex'
export default {
// ...
computed: mapState({
// 箭頭函數可使代碼更簡練
count: state => state.count,
// 傳字元串參數 'count' 等同于 `state => state.count`
countAlias: 'count',
// 為了能夠使用 `this` 擷取局部狀态,必須使用正常函數
countPlusLocalState (state) {
return state.count + this.localCount
}
})
}
當映射的計算屬性的名稱與 state 的子節點名稱相同時,我們也可以給
mapState
傳一個字元串數組。
computed: mapState([
// 映射 this.count 為 store.state.count
'count'
])
mapState
函數傳回的是一個對象。我們如何将它與局部計算屬性混合使用呢?通常,我們需要使用一個工具函數将多個對象合并為一個,以使我們可以将最終對象傳給
computed
屬性。但是自從有了對象展開運算符(現處于 ECMAScript 提案 stage-4 階段),我們可以極大地簡化寫法:
computed: {
localComputed () { /* ... */ },
// 使用對象展開運算符将此對象混入到外部對象中
...mapState({
'count',
'people'
})
}
mapState通過擴充運算符将store.state.count 映射this.count, 這個映射直接映射到目前Vue的this對象上。
是以通過this都能将這些對象點出來,這将大大的簡化了我們的代碼。同理,mapGetters, mapActions, mapMutations都是一樣的道理。
getter
Vuex 允許我們在 store 中定義“getter”(可以認為是 store 的計算屬性)。就像計算屬性一樣,getter 的傳回值會根據它的依賴被緩存起來,且隻有當它的依賴值發生了改變才會被重新計算。
為什麼要用getter
有的元件中擷取到 store 中的state, 需要對進行加工才能使用,computed 屬性中就需要寫操作函數,如果有多個元件中都需要進行這個操作,那麼在各個元件中都寫相同的函數,那就非常麻煩,這時可以把這個相同的操作寫到store 中的getters, 每個元件隻要引用getter 就可以了,非常友善。Getter 就是把元件中共有的對state 的操作進行了提取,它就相當于對state 的computed. 是以它會獲得state 作為第一個參數。
如何通路getter?
- 通過屬性通路
Getter 會暴露為
store.getters
對象,你可以以屬性的形式通路這些值:
store.getters.doneTodos // -> [{ id: 1, text: '...', done: true }]
Getter 也可以接受getters 作為第二個參數,并使用其他的getter:
getters: {
// ...
doneTodosCount: (state, getters) => {
return getters.doneTodos.length
},
doneTodos:(state,getters) => {
return state.todos
}
}
我們可以很容易地在任何元件中使用它:
computed: {
doneTodosCount () {
return this.$store.getters.doneTodosCount
}
}
注意,getter 在通過屬性通路時是作為 Vue 的響應式系統的一部分緩存其中的。
- 通過方法通路
你也可以通過讓 getter 傳回一個函數,來實作給 getter 傳參。在你對 store 裡的數組進行查詢時非常有用。
getters: {
// ...
getTodoById: (state) => (id) => {
return state.todos.find(todo => todo.id === id)
}
}
.vue檔案
store.getters.getTodoById(2) // -> { id: 2, text: '...', done: false }
注意,getter 在通過方法通路時,每次都會去進行調用,而不會緩存結果。
- 利用mapGetters
mapGetters
輔助函數僅僅是将 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 中的狀态的唯一方法是送出 mutation。Vuex 中的 mutation 非常類似于事件:每個 mutation 都有一個字元串的 事件類型 (type) 和 一個 回調函數 (handler)。這個回調函數就是我們實際進行狀态更改的地方,并且它會接受 state 作為第一個參數:
const store = new Vuex.Store({
state: {
count: 1
},
mutations: {
increment (state) {
// 變更狀态
state.count++
}
}
})
你不能直接調用一個 mutation handler。這個選項更像是事件注冊:“當觸發一個類型為
increment
的 mutation 時,調用此函數。”要喚醒一個 mutation handler,你需要以相應的 type 調用 store.commit 方法:
store.commit('increment') //increment 為mutation的type
//對象風格的送出方式(當使用對象風格的送出方式,整個對象都作為載荷傳給 mutation 函數)
store.commit({
type: 'increment',
amount: 10
})
送出載荷(Payload)
你可以向
store.commit
傳入額外的參數,即 mutation 的 載荷(payload):
mutations: {
increment (state, n) {
state.count += n
},
decrement (state, obj) {
state.count -= obj.count;
}
}
//在大多數情況下,載荷應該是一個對象,這樣可以包含多個字段并且記錄的 mutation 會更易讀
store.commit('increment', 10);
store.commit('decrement', countobj);
mapMutations輔助送出
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')`
})
}
}
mutation使用過程中需要注意的點
- 通常情況下,使用常量來定義mutation的type
- mutation必須是同步函數
- 修改對象時,需要遵循vue修改對象規則
Vue.set(obj, 'newProp', 123)
或是:
state.obj = { ...state.obj, newProp: 123 }
Action
Action 類似于 mutation,不同在于:
- Action 送出的是 mutation,而不是直接變更狀态。
- Action 可以包含任意異步操作。
讓我們來注冊一個簡單的 action:
const store = new Vuex.Store({
state: {
count: 0
},
mutations: {
increment (state) {
state.count++
}
},
actions: {
increment (context) { //context對象與store執行個體具有相同方法和屬性
context.commit('increment')
},
decrement ({ commit }) { //參數解構,當需要在一個action中觸發多個commit時,這種用法很友善
commit('decrement')
}
}
})
分發action
store.dispatch('increment')
為什麼通過action來送出mutation,而不是直接送出mutation?
一個anction是可以送出多個commit的,當這些commit直接通過mutation送出時,隻能同步進行,而action内部可以執行異步操作。
來看一個更加實際的購物車示例,涉及到調用異步 API 和分發多重 mutation
actions: {
//action支援對象方式和負載方式送出mutation
checkout ({ commit, state }, products) {
// 把目前購物車的物品備份起來
const savedCartItems = [...state.cart.added]
// 發出結賬請求,然後樂觀地清空購物車
commit(types.CHECKOUT_REQUEST)
// 購物 API 接受一個成功回調和一個失敗回調
shop.buyProducts(
products,
// 成功操作
() => commit(types.CHECKOUT_SUCCESS),
// 失敗操作
() => commit(types.CHECKOUT_FAILURE, savedCartItems)
)
}
}
mapActions輔助分發
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 什麼時候結束呢?更重要的是,我們如何才能組合多個 action,以處理更加複雜的異步流程?
首先,你需要明白
store.dispatch
可以處理被觸發的 action 的處理函數傳回的 Promise,并且
store.dispatch
仍舊傳回 Promise
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())
}
}
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 的狀态
預設情況下,子產品内部的actions,mutations, getters是注冊在全局命名空間上的,隻有state是需要通過分子產品來通路的。但是在子產品内部的mutation 和 getter,接收的第一個參數是子產品的局部狀态對象。子產品内部的action局部狀态通過
context.state
暴露出來,根節點狀态則為
context.rootState,
子產品的局部狀态
對于子產品内部的 mutation 和 getter,接收的第一個參數是子產品的局部狀态對象。
const moduleA = {
state: { count: 0 },
mutations: {
increment (state) {
// 這裡的 `state` 對象是子產品的局部狀态
state.count++
}
},
getters: {
doubleCount (state, mutations) {
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
}
}
}
命名空間
預設情況下,子產品内部的 action、mutation 和 getter 是注冊在全局命名空間的——這樣使得多個子產品能夠對同一 mutation 或 action 作出響應。
如果希望你的子產品具有更高的封裝度和複用性,你可以通過添加
namespaced: true
的方式使其成為帶命名空間的子產品。當子產品被注冊後,它的所有 getter、action 及 mutation 都會自動根據子產品注冊的路徑調整命名。例如
const store = new Vuex.Store({
modules: {
account: {
namespaced: true,
// 子產品内容(module assets)
state: { ... }, // 子產品内的狀态已經是嵌套的了,使用 `namespaced` 屬性不會對其産生影響
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']
}
}
}
}
}
})
在帶命名空間的子產品内通路全局内容(Global Assets)
如果你希望使用全局 state 和 getter,
rootState
和
rootGetters
會作為第三和第四參數傳入 getter,也會通過
context
對象的屬性傳入 action。
若需要在全局命名空間内分發 action 或送出 mutation,将
{ root: true }
作為第三參數傳給
dispatch
或
commit
即可。
modules: {
foo: {
namespaced: true,
getters: {
// 在這個子產品的 getter 中,`getters` 被局部化了
// 你可以使用 getter 的第四個參數來調用 `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) { ... }
}
}
}
帶命名空間的綁定函數
當使用
mapState
,
mapGetters
,
mapActions
和
mapMutations
這些函數來綁定帶命名空間的子產品時,寫起來可能比較繁瑣:
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']()
])
}
對于這種情況,你可以将子產品的空間名稱字元串作為第一個參數傳遞給上述函數,這樣所有綁定都會自動将該子產品作為上下文。于是上面的例子可以簡化為:
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
建立基于某個命名空間輔助函數。它傳回一個對象,對象裡有新的綁定在給定命名空間值上的元件綁定輔助函數:
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'
])
}
}
項目結構
Vuex 并不限制你的代碼結構。但是,它規定了一些需要遵守的規則:
- 應用層級的狀态應該集中到單個 store 對象中。
- 送出 mutation 是更改狀态的唯一方法,并且這個過程是同步的。
- 異步邏輯都應該封裝到 action 裡面。
隻要遵守以上規則,如何組織你的代碼結構都是ok的。在我們實際項目中,我們一般會根據項目的大小以及複雜程度對項目的結構進行區分,以下是我給出的推薦方式。
簡單且不複雜項目
- 直接寫在一個store檔案中,所有的states、actions、mutations、getters寫在一起。統一進行管理
import Vue from 'vue';
import Vuex from 'vuex';
import _ from 'lodash';
Vue.use(Vuex);
export default 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)
}
},
actions: {
toDoToday({commit}) {
coomit('TO_DO_TODAY');
}
},
mutations: {
TO_DO_TODAY(state) {
_.forEach(state.todos, todo=>{
if(!todo.done){
todo.done = true;
}
});
}
}
});
複雜項目使用modules來進行管理
目錄結構:
各個子產品分子產品1統一進行管理
import Vue from 'vue';
import Vuex from 'vuex';
import state from './states';
import mutations from './mutations';
import actions from './actions';
import getters from './getters';
import okrModules from './modules/okr';
import missionModules from './modules/mission';
Vue.use(Vuex);
export default new Vuex.Store({
modules: {
okr: okrModules,
mission: missionModules,
},
state,
mutations,
actions,
getters
});
//state.okr.currentOid 擷取okr子產品内的state
//state.mission.currentPid 擷取mission子產品内的state
将store挂載到vue身上,然後在各vue檔案中通路
//分發子產品内的action
this.$store.dispatch('okr/setObjective', null);
//擷取子產品内的getters
this.$store.getters['mission/getProjectType'];
當涉及到子產品的東西時,需要詳細的了解以上關于子產品的描述,基本就可以了解了!
參考文檔:
https://vuex.vuejs.org/zh/