实现mini vuex

import { inject, reactive, computed } from "vue";

const STORE_KEY = "__store__";

function useStore() {
    return inject(STORE_KEY);
}

function createStore(options) {
    return new Store(options);
}

class Store {
    constructor(options) {
        this._state = reactive({
            data: options.state()
        });
        this._mutations = options.mutations;
        this._actions = options.actions;
        this.getters = {}
        Object.keys(options.getters).forEach(key => {
            const fn = options.getters[key];
            this.getters[key] = computed(() => fn(this.state))
        })
    }
    get state() {
        return this._state.data
    }
    commit = (type, payload) => {
        const entry = this._mutations[type];
        entry && entry(this.state, payload)
    }
    dispatch(type, payload) {
        const entry = this._actions[type]
        return entry && entry(this, payload)
    }
    install(app) {
        app.provide(STORE_KEY, this);
    }
}

export { createStore, useStore }    
// import { createStore } from "vuex";
import { createStore } from "./gvuex";
const store = createStore({
    state() {
        return {
            count: 0,
        }
    },
    getters: {
        double(state) {
            return state.count * 2
        }
    },
    mutations: {
        add(state) {
            console.log(state);
            state.count++;
        }
    },
    actions: {
        asyncAdd({ commit }) {
            setTimeout(() => {
                commit("add");
            }, 1000);
        }
    },
})


export default store

你可能感兴趣的:(vue,javascript,前端,vue.js)