let Vue
class Store {
constructor (options) {
this.vm = new Vue({
data: () => {
return {
state: options.state
}
}
})
this.getters = {}
let getters = options.getters || {}
Object.keys(getters).forEach(gettersName => {
Object.defineProperty(this.getters, gettersName, {
get: () => {
return getters[gettersName](this.state)
}
})
})
this.mutations = {}
let mutations = options.mutations || {}
Object.keys(mutations).forEach(mutationsName => {
this.mutations[mutationsName] = payload => {
mutations[mutationsName](this.state, payload)
}
})
this.actions = {}
let actions = options.actions || {}
Object.keys(actions).forEach(actionsName => {
this.actions[actionsName] = payload => {
actions[actionsName](this, payload)
}
})
}
get state () {
return this.vm.state
}
commit = (mutationName, payload) => {
this.mutations[mutationName](payload)
}
dispatch(actionsName, payload) {
this.actions[actionsName](payload)
}
}
const install = (_Vue) => {
Vue = _Vue
Vue.mixin({
beforeCreate () {
if (this.$options.store) {
this.$store = this.$options.store
} else {
this.$store = this.$parent && this.$parent.$store
}
}
})
}
export default {
install,
Store
}
手写简易版vuex
最新推荐文章于 2024-04-29 10:42:46 发布