如今前端開發中vuejs是大部分前端工程師的首選,只要不是很小的項目都會引用vuex來進行狀態管理。最近新開展的項目比較複雜,使用vuex的地方也比較多。在此過程當中也遇到了很多問題。現在有時間正好研究下vuex框架源碼,深刻了解下他的底層實現。前端
在當前前端的spa模塊化項目中不可避免的是某些變量須要在全局範圍內引用,此時父子組件的傳值,子父組件間的傳值,兄弟組件間的傳值成了咱們須要解決的問題。雖然vue中提供了props(父傳子)commit(子傳父)兄弟間也能夠用localstorage和sessionstorage。可是這種方式在項目開發中帶來的問題比他解決的問題(難管理,難維護,代碼複雜,安全性低)更多。vuex的誕生也是爲了解決這些問題,從而大大提升咱們vue項目的開發效率。(信不信由你=-=)我接觸vue項目的這兩年,雖然一直在用vuex(用的還算熟練),可是尚未深刻的去了解過他的架構原理,最近正好有空,就來深刻學習下。vue
const store = new Vuex.Store({
state: { count: 0 },
mutations: { increment (state) {
state.count++
} } })
複製代碼
咱們設置在跟state中的屬性會被vuex存儲在根元素中vuex
this._modules = new ModuleCollection(options)//初始化
const state = this._modules.root.state//獲取定義的state
複製代碼
vuex初始化時先去獲取定義在state屬性中的值new ModuleCollection(options)進行模塊收集(從新組裝咱們定義在store中的相關屬性): 最終造成一棵module樹數組
export default class ModuleCollection {
constructor (rawRootModule) {
// register root module (Vuex.Store options)
this.register([], rawRootModule, false)
}
get (path) {
return path.reduce((module, key) => {
return module.getChild(key)
}, this.root)
}
getNamespace (path) {
let module = this.root
return path.reduce((namespace, key) => {
module = module.getChild(key)
return namespace + (module.namespaced ? key + '/' : '')
}, '')
}
update (rawRootModule) {
update([], this.root, rawRootModule)
}
register (path, rawModule, runtime = true) {
if (process.env.NODE_ENV !== 'production') {
assertRawModule(path, rawModule)
}
const newModule = new Module(rawModule, runtime)
if (path.length === 0) {
this.root = newModule
} else {
const parent = this.get(path.slice(0, -1))
parent.addChild(path[path.length - 1], newModule)
}
// register nested modules
if (rawModule.modules) {
forEachValue(rawModule.modules, (rawChildModule, key) => {
this.register(path.concat(key), rawChildModule, runtime)
})
}
}
unregister (path) {
const parent = this.get(path.slice(0, -1))
const key = path[path.length - 1]
if (!parent.getChild(key).runtime) return
parent.removeChild(key)
}
}
複製代碼
const { dispatch, commit } = this
//初始化先綁定commitpromise
this.commit = function boundCommit(type, payload, options) {
return commit.call(store, type, payload, options)
}
複製代碼
綁定以後註冊mutation(commit的屬性)
複製代碼
function registerMutation(store, type, handler, local) {
const entry = store._mutations[type] || (store._mutations[type] = [])
entry.push(function wrappedMutationHandler(payload) {
handler.call(store, local.state, payload)
})
}
複製代碼
commit(_type, _payload, _options) {
console.log('================commit=====================')
console.log(_type)
console.log(_payload)
console.log(_options)
// check object-style commit
const {
type,
payload,
options
} = unifyObjectStyle(_type, _payload, _options)
const mutation = {
type,
payload
}
//這是一個函數數組
const entry = this._mutations[type]
//判斷當前設置的屬性的值是否存在
if (!entry) {
if (process.env.NODE_ENV !== 'production') {
console.error(`[vuex] unknown mutation type: ${type}`)
}
return
}
//在執行mutation的時候,會將_committing設置爲true,執行完畢後重置,在開啓strict模式時,會監聽state的變化,當變化時_committing不爲true時會給出警告
this._withCommit(() => {
//迭代傳入的commit數組
entry.forEach(function commitIterator(handler) {
handler(payload)
})
})
this._subscribers.forEach(sub => sub(mutation, this.state))
//當開發環境是拋出警告(若是commit的屬性不存在)
if (
process.env.NODE_ENV !== 'production' &&
options && options.silent
) {
console.warn(
`[vuex] mutation type: ${type}. Silent option has been removed. ` +
'Use the filter functionality in the vue-devtools'
)
}
}
複製代碼
3.dispatch(=>actions)作了啥(初始化同commit)安全
//dispatch定義位置
this.dispatch = function boundDispatch(type, payload) {
return dispatch.call(store, type, payload)
}
複製代碼
綁定dispatchbash
function registerAction(store, type, handler, local) {
const entry = store._actions[type] || (store._actions[type] = [])
entry.push(function wrappedActionHandler(payload, cb) {
let res = handler.call(store, {
dispatch: local.dispatch,
commit: local.commit,
getters: local.getters,
state: local.state,
rootGetters: store.getters,
rootState: store.state
}, payload, cb)
//將res函數轉爲異步 promise
if (!isPromise(res)) {
res = Promise.resolve(res)
}
if (store._devtoolHook) {
return res.catch(err => {
store._devtoolHook.emit('vuex:error', err)
throw err
})
} else {
return res
}
})
}
複製代碼
註冊actionssession
dispatch(_type, _payload) {
// check object-style dispatch
const {
type,
payload
} = unifyObjectStyle(_type, _payload)
const action = {
type,
payload
}
const entry = this._actions[type]
if (!entry) {
if (process.env.NODE_ENV !== 'production') {
console.error(`[vuex] unknown action type: ${type}`)
}
return
}
try {
this._actionSubscribers
.filter(sub => sub.before)
.forEach(sub => sub.before(action, this.state))
} catch (e) {
if (process.env.NODE_ENV !== 'production') {
console.warn(`[vuex] error in before action subscribers: `)
console.error(e)
}
}
const result = entry.length > 1 ?
Promise.all(entry.map(handler => handler(payload))) :
entry[0](payload)
return result.then(res => {
try {
this._actionSubscribers
.filter(sub => sub.after)
.forEach(sub => sub.after(action, this.state))
} catch (e) {
if (process.env.NODE_ENV !== 'production') {
console.warn(`[vuex] error in after action subscribers: `)
console.error(e)
}
}
return res
})
}
複製代碼
vuex和全局變量的區別:(借用博客)前端工程師
1,【響應式】vuex的狀態存儲是響應式的,當Vue組件從store中讀取狀態的時候,若store中的狀態發生變化,那麼相應的組件也會獲得高效更新。架構
2,【不能直接改變store】不能直接改變store的變化,改變store中狀態的惟一途徑是commit mutation。方便於跟蹤每個狀態的變化。