
// 缓存Vue的实例到全局中
let _Vue
function install(vue) {
// 只在实例中挂载一次
if(Store.installed) return
Store.installed = true
_Vue = vue
// 把创建vue实例时候传入的store对象注入的vue实例上
// 混入,这里混入所有的vue实例都会有
_Vue.mixin({
beforeCreate(){
if(this.$options.store) {
// 原型上挂在操作只需要执行一次,如果是组件不执行,如果是vue实例才执行
_Vue.prototype.$store = this.$options.store
}
}
})
})
}
class Store {
constructor(options) {
// 解构出来传递的选项, 默认值是空对像
const {
state = {},
getters = {}
mutations = {},
actions = {}
} = options
this.state = _Vue.observable(state)
// getters对象中的一个个方法都需要接受state参数,且都具有返回值(返回state简单处理的结果)
this.getters = Object.create(null)
// 遍历getters对象内所有的方法,key是方法名
Object.keys(getters).forEach(key => {
Object.defineProperty(this.getters, key, {
get: () => getters[key](this.state)
})
})
this._mutations = mutations
this._actions = actions
}
}
commit(type, payload) {
this._mutations[type](this.state, payload)
}
dispatch(type, payload) {
this._actions[type](this, payload)
}
// 我们在使用 Vue.use(Vuex)
// 实现的时候,使用 new Vuex.Store()
// 所以要导出 Store,install
let _Vue;
function install(vue) {
// 只在实例中挂载一次
if (Store.installed) return;
Store.installed = true;
_Vue = vue;
// 把创建 Vue 实例时候传入的 store 对象注入到 vue 实例上
// 这里的混入所有的 Vue 实例
_Vue.mixin({
beforeCreate() {
if (this.$options.store) {
// 原型上挂在操作只需要执行一次,如果是组件不执行,如果是vue实例才执行
_Vue.prototype.$store = this.$options.store;
}
},
});
}
class Store {
constructor(options) {
// 解构出来传递的选项,默认是空对象
const {
state = {},
getters = {},
mutations = {},
actions = {},
} = options;
this.state = _Vue.observable(state);
// getters对象中的一个个方法都需要接受state参数,且都具有返回值(返回state简单处理的结果)
this.getters = Object.create(null);
// 遍历getters 对象内所有的方法, key是方法名
Object.keys(getters).forEach(key => {
Object.defineProperty(this.getters, key, {
get: () => {
getters[key](this.state);
}
});
});
this._mutations = mutations;
this._actions = actions;
}
commit(type, payload) {
this._mutations[type](this.state, payload);
}
dispatch(type, payload) {
this._actions[type](this.state, payload);
}
}