一个简单的Vuex实现回忆一下使用vuex的一些方式,包括:$store.dispatch('ActionName',data)//map的计算方法:{...mapState(['StateName']),...mapGetters(['GetterName'])}methods:{...mapMutations(['MutationName']),...mapActions(['ActionName'])}实现一个简单的vuexwriteinstall方法,注册插件,引入Vue,使用mixin挂载对象到Vue的原型中beforeCreate生命周期定义Store类,使用Vue实现传入状态以响应式方式实现commit方法,即调用mutations方法,使用响应式状态入参实现dispatch方法,即调用并返回actions方法,并使用响应状态getters可以通过传入参数实现,使用Object.keys遍历传入的getters的key,然后使用Object.defineProperty实现get方法letVue;//install方法注册插件函数install(_Vue){Vue=_Vue;Vue.mixin({beforeCreate(){if(this.$options.simplestore){Vue.prototype.$simplestore=this.$options.simplestore;}}});}classStore{constructor(options){this.state=newVue({data:options.state});this.mutations=options.mutations;this.actions=options.actions;options.getters&&this.initGetters(options.getters);}commit=(key,...data)=>{constfn=this.mutations[key];如果(fn){fn(this.state,...data);}}dispatch=(key,...data)=>{constfn=this.actions[key];if(fn){returnfn({commit:this.commit,state:this.state},...data);}}initGetters(getters){this.getters={};Object.keys(getters).forEach(key=>{Object.defineProperty(this.getters,key,{get:()=>{returngetters[key](this.state);}})})}}导出default{install,Store}源码在github,在src/simple-vuex/index.js,演示在/src/components/simple-vuex-demo.vue里
