Skip to content
On this page

provide、inject跨组件传递参

我们可以创建一个hooks,去管理这个Instance。

ts
// useTestInstance.ts 

const demoKey = Symbol('dt-demo')

type Instance = {
    a: number,
    b: number
}

// 开始注入数据
export function createDemoInstance(instance: Instance) {
    provide(demoKey, instance)
}

// 获取注入的参数
export function getDemoInstance(): Instance {
    return inject(tableKey)
}

父组件:

ts
createDemoInstance({
    a: 1,
    b: 2
})

子组件

ts
const injectData = getDemoInstance()