- 获取当前table组件实例
const table = getCurrentInstance() as Table<Row>
- 用symbol类型定义一个依赖注入键
import type { InjectionKey } from 'vue'
import type { DefaultRow, Table } from './table/defaults'
// 依赖注入键,用于在组件中获取 Table 实例
export const TABLE_INJECTION_KEY: InjectionKey<Table<DefaultRow>> =
Symbol('ElTable')
- 将当前 Table 组件实例注入到组件树中
provide(TABLE_INJECTION_KEY, table)
这行代码将当前 Table 组件实例注入到组件树中,使所有子组件(table-body、table-header、table-footer 等)都能通过 inject(TABLE_INJECTION_KEY) 获取父级 Table 实例,实现跨层级组件通信,避免 props 层层传递。这是 Vue 3 依赖注入模式的典型应用。
- 子组件中使用父组件Table实例
import { TABLE_INJECTION_KEY } from '../tokens'
const parent = inject(TABLE_INJECTION_KEY) as Table<T>
// 打印父组件的props highlightCurrentRow
console.log(parent?.props.highlightCurrentRow)