如何避免【Vue warn】:未找到注入“xxxx”

har*_*aga 1 typescript vue.js nuxt.js vuejs3

我在 nuxt 组合 API 中使用注入/提供模式。例如,组件 A 注入组件 B 提供的功能,组件 B 是组件 A 的父组件,如下所示。

//Component B 
const test = () => {}
provide('test', test)
Run Code Online (Sandbox Code Playgroud)
//Component A 
const test = inject<Function>('test')
Run Code Online (Sandbox Code Playgroud)

但是,当我想使用组件 A 而不使用组件 B 时,控制台上会显示此警告。我明白它的意思,但在这种情况下它不需要使用“测试”功能。有什么办法可以避免这个警告吗?

[Vue warn]:未找到注入“测试”

ton*_*y19 8

为了避免警告,请指定默认值( 的第二个参数inject()):

const test = inject<Function>('test', () => {})
Run Code Online (Sandbox Code Playgroud)

演示