【发布时间】:2021-03-09 13:58:18
【问题描述】:
从我找到的文档中学习 Vue Composition API(和 TypeScript),我应该使用 ref(null) 来供我在 <template>...</template> 中的子组件使用。
这个子组件有open()之类的方法,我是这样访问它的:
setup() {
const subcomponentRef= ref(null);
subcomponentRef.value.open();
return { subcomponentRef };
}
我同意这可能会显示错误Object is possibly 'null'. 指向subcomponentRef.value,但奇怪的是即使我添加了条件if (subcomponentRef !== null && subcomponentRef.value !== null) { ... },它仍然显示该错误。 为什么?
还尝试像subcomponentRef?.value?.open() 一样访问它,但我收到此错误Property 'open' does not exist on type 'never'.。
还尝试添加 非空断言,例如 confirmation.value!.open(); 并收到相同的错误 Property 'open' does not exist on type 'never'.。
知道这里有什么问题吗?或者我应该用实际组件预定义它而不是使用ref(null)?但我不知道如何正确地做到这一点,在文档中找不到。
【问题讨论】:
-
您好像在引用一个组件,请分享您是如何导入它的
-
我正在使用 NuxtJS 及其自动注册组件的组件模块,但可以说我不使用它,我会像
import subcomponent from './subcomponent.vue';和模板<subcomponent ref="subcomponentRef" />那样使用它跨度>
标签: typescript vue.js vuejs3 vue-composition-api