侧边栏壁纸
  • 累计撰写 56 篇文章
  • 累计创建 12 个标签
  • 累计收到 9 条评论

目 录CONTENT

文章目录

Vue3 依赖注入的TS解决方案——InjectionKey

Kirito
2026-06-29 / 0 评论 / 0 点赞 / 2 阅读 / 2034 字 / 正在检测是否收录...

What——什么是InjectionKey

interface InjectionConstraint<T> {}

export type InjectionKey<T> = symbol & InjectionConstraint<T>

通过源码可以看出,InjectionKey只是一个空接口,并没有其它的逻辑,在编译后会被移除。

Why——为什么用

Vue依赖注入provide/inject时,在Typescript环境下始终存在一个类型标注的问题,inject接受到的参数会被推导为any类型,无法在Typescript下形成有效的类型检查,而InjectionKey可以帮助开发者很好的解决这个问题。

How——怎么用

// 定义 keys.ts
import type { InjectionKey, Ref } from 'vue'

export const nameKey: InjectionKey<Ref<string>> = Symbol('name')
// 注入依赖
import { provide } from 'vue'
import { nameKey } from './keys'

const name = ref('Kirito')

provide(nameKey, name)
// 取值
import { inject } from 'vue'
import { nameKey } from './keys'

const name = inject(nameKey)
// 默认值
const name = inject(nameKey, ref('Abc'))

这样在inject中就能正确获取到值对应的类型。

0

评论区