vuex原始碼實現

2021-09-25 15:48:18 字數 2653 閱讀 4723

let vue;

/** * [自定義foreach迴圈]

* @author suzhe

* @datetime 2019-07-28t11:12:17+0800

* @param obj [description]

* @param classback [description]

*/const foreach = (obj, classback) => )

}/**

* 格式化模組state

*/class modulecollection

register(path, rootmodule),

state: rootmodule.state

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

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

} if(rootmodule.modules))

} }}/**

* [將結果掛載 getters mutations actions]

* @author suzhe

* @datetime 2019-07-28t13:02:26+0800

*/const installmodule = (store, state, path, rootmodule) => ,state)

//設定屬性

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

} //先處理根模組的getters屬性

let getters = rootmodule._raw.getters

if(getters)

})})

} let mutations = rootmodule._raw.mutations

if(mutations))

arr.push(fn)

})} let actions = rootmodule._raw.actions

if(actions))

arr.push(fn)

})} foreach(rootmodule._children, (name, val) => )

}/**

* store 物件

*/class store

// })

// let getters = options.getters || {}

// this.getters = {}

// //把getters屬性定義到 this.getters 中,並且根據狀態變化 重新執行此函式

// foreach(getters, (name, fn) =>

// })

// })

// let mutations = options.mutations || {}

// this.mutations = {}

// //把mutations屬性定義到 this.mutations 中,並且根據使用者觸發 重新執行此函式

// foreach(mutations, (name, fn) =>

// })

// //獲取actions

// let actions = options.actions || {}

// this.actions = {}

// foreach(actions, (name, fn) =>

// })

// this.modules = new modulecollection(options)

// //防止外部呼叫actionsthis指向全域性的問題 或es7語法

// // let = this

// // this.dispatch = (...arg)=>

// // this.commit = (...arg)=>

// }

// constructor(options)

})this.getters = {}

this.mutations = {}

this.actions = {}

this.modules = new modulecollection(options)

console.log(this.modules)

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

} //防止外部呼叫actionsthis指向全域性的問題

dispatch = (type, payload) =>

commit = (type, payload) =>

get state()

}/**

* [install外掛程式]

* @author suzhe

* @datetime 2019-07-28t11:12:56+0800

* @param _vue [description]

*/const install = _vue =>else

} })

}export default

vuex簡單原始碼實現

let vue 在變數宣告 不然會儲存 class store vue.store 對應使用結構 export default install用於use外掛程式 this getters 初始化物件 用於獲取store裡面的getters屬性 this mutations option.mutati...

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原始碼

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 ...