手动实现简单的vuex

2019-10-06  本文已影响0人  key君
官方vuex

vue add vuex

main.js
import store from './kstore'
new Vue({
  el: '#app',
  router,
  store,
  render: h => h(App)
})
kstore.js
import Vue from 'vue'
import Vuex from './kvuex'

Vue.use(Vuex)

export default new Vuex.Store({
    state:{
        count: 10
    },
    mutations:{
        increment(state){
            state.count += 1;
        }
    },
    actions:{
        asyncAdd({commit}){
            commit("increment")
        },
        increment({getters,commit}){
            if(getters.left > 0){
                commit("increment");
                return true;
            }
            return false;
        },
        asyncIncrement({dispatch}){
            return new Promise(resolve => {
                setTimeout(() => {
                    resolve(dispatch("increment"));
                },1000);
            });
        }
    }
})
kvuex.js
let Vue;

function install(_Vue) {
    Vue = _Vue;
    Vue.mixin({
        beforeCreate(){
            if(this.$options.store){
                Vue.prototype.$store = this.$options.store;
            }
        }
    })
}

class Store {
    constructor(options = {}){
        this.state = new Vue({
            data: options.state
        })
        this.mutations = options.mutations || {};
        this.actions = options.actions || {};
    }
    //type是mutations中的函数名
    commit = (type,arg) =>{
        //执行mutations里面的函数
        this.mutations[type](this.state,arg)
    }
    dispatch(type,arg){
        this.actions[type]({
            commit: this.commit,
            state: this.store
        },arg)
    }
}

export default {Store,install}
使用
<p>{{$store.state.count}}</p>
this.$store.dispatch("asyncAdd")
this.$store.commit("increment");
上一篇下一篇

猜你喜欢

热点阅读