共享状态必须符合两个条件:
- 响应式:当状态改变时,使用它们的组件也应更新
- 可用性:可以在任何组件中访问状态
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)