记一次vuex简约版实战

123 阅读1分钟

在极客时间学习vue3,不得说老师讲的真好,一步步实操。

vuex模拟实战

import { inject, reactive } from 'vue'
//provide 全局提供数据
// inject 任意子组件中获取provide提供的数据

const STORE_KEY = '__store__'
function useStore() {
    return inject(STORE_KEY) // 子组件调用useStore时 ,通过STORE_KEY拿到key对应的value
}
function createStore(options) {
    return new Store(options)
}

class Store {
    constructor(options) {
        this.$options = options
       this.__state__ = reactive({ // 把用户传入的state对象编程响应式数据,并保存内部变量_state上面
           data:options.state()
       })
        this._mutations = options.mutations // 直接保存用户的mutations
    }
    get state() {
        return this.__state__.data
    }

    commit = (type, payload) => {
        const entry = this._mutations[type]
        entry && entry(this.state, payload)
    }
    install(app) { // 在main.js 中 用use调用的时候 自动触发install 方法
        app.provide(STORE_KEY, this)
    }
}

export { createStore, useStore }

记录一下!! !