Appearance
同一个vue文件,不同的hook之间共享数据(vue3)
- defineCtxState 定义共享数据
- usCtxState 获取共享数据
defineCtxState
定义当前组件作用域的共享数据
Parameters:
data: - 需要共享的数据
Examples:
ts
// state: 共享数据的只读代理
interface IState {
count: number
}
const [state, setState] = defineCtxState<IState>({ count: 0 })
//推荐函数写法
setState((state) => {
state.count = 2
})
//setState: 更新共享数据的方法,会合并旧数据
setState({ count: 2 })
//直接修改定义的数据,为了避免副作用,子hook中不推荐 (useCtxState是只读的)
state.count = 2usCtxState
获取当前组件作用域{@link defineCtxState}定义的共享数据
Examples:
ts
// state: 共享数据的只读代理
const [state, setState] = useCtxState<IState>()
//在获取数据的地方,建议使用函数式更改数据
setState((state) => {
state.count = 2
})
//setState: 更新共享数据的方法
setState({ count: 2 })
state.count = 2 //子hook中useCtxState 不推荐,只读的