vue3继承ref
时间: 2025-04-29 22:55:42 浏览: 22
### Vue3 中 `ref` 的继承
在 Vue 3 中,`ref` 可用于创建响应式的引用对象。当涉及到父子组件之间的通信时,父组件可以通过 `ref` 来访问子组件的属性和方法。为了使父组件能够访问 `<script setup>` 子组件内部的内容,子组件需要使用 `defineExpose` 显式暴露特定的部分[^4]。
#### 创建并暴露子组件中的 `ref`
考虑一个场景,在子组件中有一个 DOM 元素或者另一个组件实例希望被父组件所控制或读取:
```html
<!-- ChildComponent.vue -->
<script setup>
import { ref } from 'vue';
const childElement = ref(null);
// 暴露给父组件的对象
defineExpose({
childElement,
});
</script>
<template>
<div ref="childElement">我是子组件内的元素</div>
</template>
```
上述代码片段展示了如何在一个采用 `<script setup>` 语法糖写的子组件里定义了一个名为 `childElement` 的 `ref` 并将其暴露出去。
#### 父组件中获取并操作子组件的 `ref`
接着看下父组件是如何利用这个已暴露出来的 `ref` 进行交互的:
```html
<!-- ParentComponent.vue -->
<template>
<ChildComponent ref="myChild"/>
<button @click="handleClick">点击我来查看子组件DOM节点</button>
</template>
<script setup>
import { ref } from 'vue';
import ChildComponent from './components/ChildComponent.vue';
const myChild = ref(null);
function handleClick() {
console.log(myChild.value.childElement); // 访问子组件暴露出的 ref
}
</script>
```
这里的关键在于父组件通过模板上的 `ref` 属性指定了一个变量名 (`myChild`) ,之后就可以在这个变量上调用由子组件 `defineExpose` 出来的成员了。
#### 关于 TypeScript 支持
对于带有 TypeScript 类型支持的项目来说,可以为 `defineExpose` 提供类型声明以获得更好的开发体验:
```typescript
// ChildComponent.vue with TS support
<script lang="ts" setup>
import { Ref, defineExpose, ref } from 'vue';
let childElement: HTMLElement | null = null;
const elRef = ref(childElement) as Ref<typeof childElement>;
defineExpose<{
elRef: typeof elRef;
}>({
elRef,
});
</script>
```
这样不仅可以让 IDE 更好地理解代码结构,而且也能减少运行时错误的发生几率。
阅读全文
相关推荐


















