###### 如果之前未使用過 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
更改 Vuex 的 store 中的狀態的唯一方法是提交 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 對象就有可能變得相當臃腫。這時我們可以將 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 相關代碼分割到模塊中。下面是項目結構示例: