我正在尝试使用 Composition API 在 Vue 3 中获取 $refs。这是我的模板,它有两个子组件,我需要引用一个子组件实例:
<template>
<comp-foo />
<comp-bar ref="table"/>
</template>
在我的代码中,我使用 Template Refs : ref 是一个特殊的属性,它允许我们在安装后获得对特定 DOM 元素或子组件实例的直接引用。
如果我使用 Options API,那么我没有任何问题:
mounted() {
console.log("Mounted - ok");
console.log(this.$refs.table.temp());
}
但是,使用 Composition API 时出现错误:
setup() {
const that: any = getCurrentInstance();
onMounted(() => {
console.log("Mounted - ok");
console.log(that.$refs.table.temp());//ERROR that.$refs is undefined
});
return {};
}
谁能说如何使用 Composition API 做到这一点?
原文由 Pavel_K 发布,翻译遵循 CC BY-SA 4.0 许可协议
您需要在设置中创建 ref const 然后将其返回以便可以在 html 中使用。