el-table源码解读1——InjectionKey依赖注入在复杂组件中的应用

6 阅读1分钟
  1. 获取当前table组件实例
const table = getCurrentInstance() as Table<Row>
  1. 用symbol类型定义一个依赖注入键
import type { InjectionKey } from 'vue'
import type { DefaultRow, Table } from './table/defaults'

// 依赖注入键,用于在组件中获取 Table 实例
export const TABLE_INJECTION_KEY: InjectionKey<Table<DefaultRow>> =
  Symbol('ElTable')

  1. 将当前 Table 组件实例注入到组件树中
provide(TABLE_INJECTION_KEY, table)

这行代码将当前 Table 组件实例注入到组件树中,使所有子组件(table-body、table-header、table-footer 等)都能通过 inject(TABLE_INJECTION_KEY) 获取父级 Table 实例,实现跨层级组件通信,避免 props 层层传递。这是 Vue 3 依赖注入模式的典型应用。

  1. 子组件中使用父组件Table实例
import { TABLE_INJECTION_KEY } from '../tokens'
const parent = inject(TABLE_INJECTION_KEY) as Table<T>

// 打印父组件的props highlightCurrentRow
console.log(parent?.props.highlightCurrentRow)