首先看一下symbol的使用:
Symbol - JavaScript | MDN (mozilla.org)
太长不看的大概意思就是,创建一个唯一值。
而在vue的依赖注入功能中,就可以使用symbol作为key值。
以EP为例,这是form的依赖提供:
provide(
formContextKey,
reactive({
...toRefs(props),
emit,
resetFields,
clearValidate,
validateField,
addField,
removeField,
...useFormLabelWidth(),
})
)
export const formContextKey: InjectionKey<FormContext> =
Symbol('formContextKey')
export declare interface InjectionKey<T> extends Symbol {
}
formContextKey 是个键值,FormContext 则是要提供的类型,接受一个symbol,这里T的传递一开始有点没看懂,后面发现,T的存在是为了provide方法的类型推导,自己写了个类似的。
export declare function provide<T>(key: InjectionKey<T> | string | number, value: T): void;
interface Test<T> extends String {
}
export const test: Test<{ a: string }> = 'test'
inject的话则只需要同样的导入该键值即可,为什么非要用 symbol ?单纯为了防止重复...
const formContext = inject(formContextKey, undefined)