let _Vue = null
class Store {
constructor( options ) {
const {
state = {},
getters = {},
mutations = {},
actions = {}
} = options
//state是响应式的
this.state = _Vue.observable(state)
//通过数据劫持的get方式给getters传入参数state
Object.keys(getters).forEach( key => {
Object.defineProperty( this.getters, key, {
get () {
return getters[key](state)
}
})
})
this._mutations = mutations
this._actions = actions
}
commit (key, payload) {
this._mutations[key](this.state, payload)
}
dispatch (key, payload) {
this._actions[key](this, payload)
}
}
function install (Vue) {
_Vue = Vue
//通过混入的方式将实例化Vue时传入的store绑定到原型对象上
_Vue.mixin({
beforeCreate () {
if( this.$options.store ) {
_Vue.prototype.$store = this.$options.store
}
}
})
}
export default {
Store,
install
}
模拟实现简易版Vuex
最新推荐文章于 2022-09-08 17:23:00 发布