手写vuex

57 阅读1分钟
let _Vue = null
class Store {
	constructor(options) {
		const { state, getters, mutations, actions } = options
		this.state = _Vue.observable(state)
		this.getters = Object.create(null)
		Object.kes(getters).forEach((key) => {
			Object.defineProperties(this.getters, key, {
				get: () => getters[key](state)
			})
		})
		this._mutations = mutations
		this._actions = actions
	}
	commit(type, payload) {
		this._mutations[type](this.state, payload)
	}
	dispatch(type, payload) {
		this._actions[type](this, payload)
	}
}
function install(Vue) {
	_Vue = Vue
	_Vue.mixin({
		beforeCreate() {
			if (this.$options.store) {
				_Vue.prototype.$store = this.$options.store
			}
		}
	})
}
export default {
	install,
	Store
}

import Vue from 'vue';
import myvuex from './myvuex';
import globalStore from '@store';
import setting from './setting';

Vue.use(myvuex);

const store = new Vuex.Store({
	modules: {
		...globalStore,
		setting,
	},
});

export default store;