Vue 之狀態管理 vuex 學習
Vuex 介紹
Vuex 是一個專為 Vue.js 應用程式開發的 狀態管理模式
。
它採用集中式儲存管理應用的所有元件的狀態,並以相應的規則保證狀態以一種可預測的方式發生變化。
舉一個很常見的例子:子元件呼叫父元件一般通過event 來完成,比如 this.$emit()
…一旦業務複雜,元件越來越多,呼叫關係越來越複雜的時候,我們可以用Vuex 來集中管理這些元件的變化
一.狀態管理模式
new Vue({
// state
data () {
return {
count: 0
}
},
// view
template: `<div>{{ count }}</div>`,
// actions
methods: {
increment () {
this.count++
}
}
})
這個狀態自管理應用包含以下幾個部分:
- state,驅動應用的資料來源;
- view,以宣告方式將 state 對映到檢視;
- actions,響應在 view 上的使用者輸入導致的狀態變化。
二.最簡單的store
建立一個簡單的store示例:
// 如果在模組化構建系統中,請確保在開頭呼叫了 Vue.use(Vuex)
const store = new Vuex.Store({
state: {count : 0},
mutations: {
increment (state) {
state.count++
}
}
})
- 獲取狀態物件:
store.state
- 觸發狀態更新:
store.commit('increment')
我們通過store.commit('increment')
提交到mutations
來改變count
的值
三.Store (單一狀態樹)
Vuex 使用單一狀態樹——是的,用一個物件就包含了全部的應用層級狀態。
至此它便作為一個“唯一資料來源 (SSOT)”而存在。這也意味著,每個應用將僅僅包含一個 store 例項
在Vue元件中展示狀態
最簡單的辦法是使用計算屬性:
// 建立一個 Counter 元件
const Counter = {
template: `<div>{{ count }}</div>`,
computed: {
count () {
return store.state.count
}
}
}
每當 store.state.count
變化的時候, 都會重新求取計算屬性,並且觸發更新相關聯的 DOM。
Vuex 通過 store 選項,提供了一種機制將狀態從根元件“注入”到每一個子元件中(需呼叫 Vue.use(Vuex)
):
const app = new Vue({
el: '#app',
// 把 store 物件提供給 “store” 選項,這可以把 store 的例項注入所有的子元件
store,
components: { Counter },
template: `
<div class="app">
<counter></counter>
</div>
`
})
//通過在根例項中註冊 store 選項,該 store 例項會注入到根元件下的所有子元件中
//count 可以通過 this.$store 來訪問到
const Counter = {
template: `<div>{{ count }}</div>`,
computed: {
count () {
return this.$store.state.count
}
}
}
mapState 輔助函式
當一個元件需要獲取多個狀態時候,將這些狀態都宣告為計算屬性會有些重複和冗餘。
為了解決這個問題,我們可以使用 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: {
localComputed () { /* ... */ },
// 使用物件展開運算子將此物件混入到外部物件中
...mapState({
// ...
})
}
四.Getter
Vuex 允許我們在 store 中定義“getter”(可以認為是 store 的計算屬性)。
就像計算屬性一樣,getter 的返回值會根據它的依賴被快取起來,且只有當它的依賴值發生了改變才會被重新計算。
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 也可以接受其他 getter 作為第二個引數:
getters: {
// ...
doneTodosCount: (state, getters) => {
return getters.doneTodos.length
}
}
store.getters.doneTodosCount // -> 1
也可以通過讓 getter 返回一個函式,來實現給 getter 傳參。在你對 store 裡的陣列進行查詢時非常有用。
getters: {
// ...
getTodoById: (state) => (id) => {
return state.todos.find(todo => todo.id === id)
}
}
store.getters.getTodoById(2) // -> { id: 2, text: '...', done: false }
mapGetters 輔助函式
import { mapGetters } from 'vuex'
export default {
// ...
computed: {
// 使用物件展開運算子將 getter 混入 computed 物件中
...mapGetters([
'doneTodosCount',
'anotherGetter',
// ...
])
}
}
如果你想將一個 getter 屬性另取一個名字,使用物件形式
mapGetters({
// 對映 `this.doneCount` 為 `store.getters.doneTodosCount`
doneCount: 'doneTodosCount'
})
五.Mutation
更改 Vuex 的 store 中的狀態的唯一方法是提交 mutation
,mutation 可以簡單理解成更改 store 的控制器
每個 mutation 都有一個字串的 事件型別 (type)
和 一個回撥函式 (handler)
。
這個回撥函式就是我們實際進行狀態更改的地方,並且它會接受 state 作為第一個引數:
const store = new Vuex.Store({
state: { count: 1},
mutations:{
increment : state = >{
// 變更狀態
state.count++
}
//提交載荷(Payload)
incrementpara : (state,payload) = >{
state.count += payload.amount
}
}
})
需要通過:
1. store.commit('increment')
來 呼叫 increment
2. store.commit('incrementpara',{amount : 10})
來 呼叫 incrementpara
物件風格的提交方式(handler 不變)
store.commit({
type: 'increment',
amount: 10
})
注意事項
最好提前在你的 store 中初始化好所有所需屬性。
當需要在物件上新增新屬性時,你應該
使用 Vue.set(obj, 'newProp', 123)
,
或者以新物件替換老物件。例如,利用 stage-3 的物件展開運算子我們可以這樣寫:
state.obj = { ...state.obj, newProp: 123 }
Mutation 必須是同步函式
在元件中提交 Mutation
你可以在元件中使用 this.$store.commit('xxx')
提交 mutation,
或者使用 mapMutations 輔助函式將元件中的 methods 對映為store.commit
呼叫(需要在根節點注入 store)
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')`
})
}
}
六.Action
所有的Mutation 都是同步方法,如果變更多個元件的狀態,我們無法知道哪一個元件先回調,這時候就引入了Action
Action 類似於 mutation,不同在於:
- Actio 提交的是 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。
分發 Action
store.dispatch('increment')
為什麼不直接分發mutation? mutation 受同步限制
actions: {
incrementAsync ({ commit }) {
setTimeout(() => {
commit('increment')
}, 1000)
}
}
// 以載荷形式分發
store.dispatch('incrementAsync', {
amount: 10
})
// 以物件形式分發
store.dispatch({
type: 'incrementAsync',
amount: 10
})
在元件中分發 Action
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')`
})
}
}
七.Module
當Store比較複雜的時候,vue把Store分割成module
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 的狀態
模組動態註冊
// 註冊模組 `myModule`
store.registerModule('myModule', {
// ...
})
// 註冊巢狀模組 `nested/myModule`
store.registerModule(['nested', 'myModule'], {
// ...
})