手写一个vue3的迷你vuex

53 阅读1分钟

废话不多说,就是没有废话,一名合格的前端工程师直接看代码

import { inject, provide, reactive } from 'vue'
const STORE_KEY = '__store__'
const useStore = () => {
  return inject(STORE_KEY)
}

const createStore = (Options) => {
  return new Store(Options)
}

class Store {
  constructor(options) {
    this._state = reactive({
      data: options.state(),
    })
    this._mutations = options.mutations
  }
  install(app) {
    app.provide(STORE_KEY, this)
  }
  get state() {
    return this._state.data
  }
  commit = (type, payload) => {
    const entry = this._mutations[type]
    entry && entry(this.state, payload)
  }
}
export { useStore, createStore }