- 实现一个插件:挂载 $store
- 实现store
以下是实现的一份简易版 vuex 源码:
// 一、缓存Vue构造函数
let Vue;
// 二、核心:声明一个Store类
class Store {
constructor(options) {
//访问state方法:this.$store.state.xxx
this._vm = new Vue ({
// Vue会把data里的数据变为响应式,
// 在这里给state做响应式处理
// 用一个方法将这个state暴露到外边,
// 将new Vue ( )赋值给一个变量,this.state
data: {
$$state: options.state
}
})
this.mutations = options.mutations
this.actions = options.actions
this.commit = this.commit.bind(this)
this.dispatch = this.dispatch.bind(this)
this.getters = { }
options.getters && this.handleGetters(options.getters)
}
handleGetters(getters){
Object.keys(getters).map((key) => {
Object.defineProperty(this.getters, key, {
get: () => getters[key](this.state)
})
})
}
get state(){
return this._vm._data.$$state
}
set state(){
console.log("Please use replaceState to reset state")
}
// 实现一个commit方法,调用时:commit (fn, param2)
// fn为mutations里的方法
commit (type, payload) {
const entry = this._mutations[type];
if(!entry) {
console.log.error("unknown mutations type")
}
entry(this.state, payload)
}
dispatch(type, payload) {
const entry = this._actions[type];
if(!entry) {
console.log.error("unknown actions type")
}
// this上找commit和dispatch
entry(this, payload)
}
}
// 三、Store类上添加一个静态的install方法
// Store.install = () => {}
// 换一种方式:
const install = (_Vue) =>{
Vue = _Vue //缓存Vue
// 做一个全局混入
Vue.mixin({
beforeCreate() {
if(this.$options.store) {
Vue.prototype.$store = this.$options.store
}
}
})
}
// 四、导出
export default { Store, install };
版权声明:本文为weixin_41319237原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。