Vue3.0简单替代Vuex

共享状态必须符合两个条件:

  • 响应式:当状态改变时,使用它们的组件也应更新
  • 可用性:可以在任何组件中访问状态

hooks写法

import { reactive, provide, inject, readonly } from 'vue'

export const stateSymbol = Symbol('state')
export const createStore = () => {
    const state = reactive({
        count: 0
    });
    const increment = () => state.count++;
    return {
        increment,
        state: readonly(state)
    }
}
export const useState = () => inject(stateSymbol)
export const provideState = () => provide(createStore)
posted @ 2021-03-29 16:14  671_MrSix  阅读(425)  评论(0编辑  收藏  举报