使用vue3 CompositionAPI手?jǐn)]vuex,更好的理解vuex的工作原理
需要到的api
provide 頂層組件提供數(shù)據(jù)
inject 任意子組件獲取數(shù)據(jù)
reactive 將state變成響應(yīng)式數(shù)據(jù)
1. 從vue3中倒入API: inject,reactive
import {inject, reactive} from 'vue'
2. 聲明一個(gè)store的key
const STORE_KEY = '__store__'
3. 子組件通過(guò)調(diào)用函數(shù)useStore獲取頂層組件提供的數(shù)據(jù)
function useStore(){
return inject(STORE_KEY)
}
4. 用戶通過(guò)調(diào)用createStore函數(shù)初始化store對(duì)象
function createStore(options){
return new Store(options)
}
5. Store對(duì)象的實(shí)現(xiàn)
class Store {
constructor(options){
// 存儲(chǔ)state,通過(guò)reactive把state變成響應(yīng)式數(shù)據(jù)
this._state = reactive({
data: options.state()
})
// 存儲(chǔ)mutations
this._mutations = options.mutations
}
// 返回state對(duì)象, 這里使用get語(yǔ)法 方便訪問(wèn)this.state時(shí)直接返回data
get state(){
return this._state.data
}
// commit 用戶提交mutations時(shí),先判斷是否有這個(gè)mutations函數(shù)
// 有才調(diào)用,并傳入state和新數(shù)據(jù)提供給用戶使用
commit = (type, payload) => {
const entry = this._mutations[type]
entry && entry(this.state, payload)
}
// install方法,提供給Vue.use進(jìn)行全局注冊(cè)
// 全局注冊(cè)組件時(shí),調(diào)用全局組件的provide
// provide函數(shù)接收一個(gè)key,一個(gè)value
// 這里把STORE_KEY作為key,把this作為value也就是Store對(duì)象
install(app){
app.provide(STORE_KEY, this)
}
}
// 最后倒出createStore,和useStore
export {createStore, useStore}


浙公網(wǎng)安備 33010602011771號(hào)