简单的vuex实现
实现一个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获取并执行对应 actionconstructor(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);
}
【简单的vuex实现】实现
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
});
推荐阅读
- 热闹中的孤独
- JAVA(抽象类与接口的区别&重载与重写&内存泄漏)
- 放屁有这三个特征的,请注意啦!这说明你的身体毒素太多
- 一个人的旅行,三亚
- 布丽吉特,人生绝对的赢家
- 慢慢的美丽
- 尽力
- 一个小故事,我的思考。
- 家乡的那条小河
- 《真与假的困惑》???|《真与假的困惑》??? ——致良知是一种伟大的力量