共计 1416 个字符,预计需要花费 4 分钟才能阅读完成。
实现一个 vuex 插件 pvuex
初始化: Store 申明、install 实现,vuex.js:
let Vue;
// 定义 install 办法 实现赋值与注册
function install(_Vue) {
Vue = _Vue;
Vue.mixin({beforeCreate() {if (this.$options.store) {Vue.prototype.$store = this.$options.store;}
}
});
}
// 定义 sotre 类, 治理响应式状态 state
class Store {constructor(options = {}) {
this._vm = new Vue({
data: {$$state:options.state}
});
}
get state() {return this._vm._data.$$state}
set state(v) {return v}
}
function install(_Vue) {
Vue = _Vue;
Vue.mixin({beforeCreate() {if (this.$options.store) {Vue.prototype.$store = this.$options.store;}
}
});
}
export default {Store, install};
实现 commit
: 依据用户传入 type 获取并执行对应 mutation
// class Store...
constructor(options = {}) {
// 保留用户配置的 mutations 选项
this._mutations = options.mutations || {}}
commit(type, payload) {
// 获取对应的 mutation
const entry = this._mutations[type]
// 传递 state 给 mutation
entry && entry(this.state, payload);
}
实现 actions
: 依据用户传入 type 获取并执行对应 action
constructor(options = {}) {this._actions = options.actions || {}
const store = this
const {commit, action} = store
// 将上下文指定为 sotre 实例
this.commit = this.commit.bind(this)
this.dispatch = this.dispatch.bind(this)
}
dispatch(type, payload) {
// 获取对应的 action
const entry = this._actions[type]
return entry && entry(this, payload);
}
实现 getters
, 并利用 computed 属性缓存.
// class Store
const store = this
const computed = {}
Object.keys(this._getters).forEach(key => {computed[key] = function(){store._getters[key](store.state)
}
Object.defineProperty(this.getters, key, {get(){return store._vm[key]
},
set(v){console.log(v)
}
})
});
this._vm = new Vue({
data: {$$state:options.state},
computed
});
正文完