美文网首页
手动实现简单的vuex

手动实现简单的vuex

作者: key君 | 来源:发表于2019-10-06 01:59 被阅读0次
    官方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");
    

    相关文章

      网友评论

          本文标题:手动实现简单的vuex

          本文链接:https://www.haomeiwen.com/subject/bypypctx.html