vuex原始碼學習筆記

2021-09-24 09:17:05 字數 1759 閱讀 8408

import vuex from 'vuex'

import vue from 'vue'

vue.use(vuex)

export default new vuex.store(,

getters = {},

mutations = {},

actions = {}

})複製**

vue.use()方法必須包含install方法,目的就是把外掛程式掛載到vue上 vue-router, vuex都是同樣的原理

install方法的實現

let vue

let install = (_vue) => else }})

}複製**

class store  = options

this.getters = object.create(null)

this.actions = object.create(null)

this.mutations = object.create(null)

// module收集器

this.modules = new modulecollection(options)

this._vm = new vue(

})const = this

this.dispatch = (type) =>

this.commit = () =>

// 初始化module,同時遞迴註冊所有module

installmodule(this, state, , this.modules.root)

}get state

() dispatch (type)

commit (type)

}複製**

modulecollection 主要將傳入的 options 物件整個構造為乙個 module 物件, 並迴圈呼叫 register 為其中的 modules 屬性進行模組註冊, 使其都成為 module 物件, 最後 options 物件被構造成乙個完整的元件樹.

class modulecollection 

register (path, rawmodule) ,

state: rawmodule.state

}if (path.length === 0 ) else , this.root)

parent._children[path[path.length - 1]] = newmodule

}if (rawmodule.modules) )}}

}複製**

註冊mutation、action以及getter,同時遞迴安裝所有子module。

function installmodule (store, rootstate, path, rootmodule) , rootmodule)

vue.set(parent, path[path.length - 1], rootmodule.state)

}if (rootmodule._raw.getters)

})})

}if (rootmodule._raw.actions) )})}

if (rootmodule._raw.mutations) )})}

foreach(rootmodule._children, (childname, module) => )

}複製**

vuex 原始碼分析 vuex原始碼解讀 簡易實現

原始碼解讀 開始之前,先貼個大綱 首先,我們從使用方法入手,一步步來看 store.js import vue from vue import vuex from vuex vue.use vuex export default new vuex.store data 2000 main.js im...

vuex原始碼實現

let vue 自定義foreach迴圈 author suzhe datetime 2019 07 28t11 12 17 0800 param obj description param classback description const foreach obj,classback 格式化模...

手寫Vuex原始碼

vuex是基於vue的響應式原理基礎,所以無法拿出來單獨使用,必須在vue的基礎之上使用。main.js 1 import store form store 引入乙個store檔案2 3new vue store.js 1 import vuex from vuex 2 3vue.use vuex ...