vue-property-decorator @Ref
时间: 2025-06-15 10:35:09 浏览: 8
### @Ref 装饰器的用法与示例
`@Ref` 是 `vue-property-decorator` 提供的一个装饰器,用于将 Vue 的 `$refs` 属性绑定到类的实例属性上[^1]。通过使用 `@Ref`,开发者可以直接在 TypeScript 或 JavaScript 类中以类型安全的方式访问组件或 DOM 元素的引用。
以下是关于 `@Ref` 装饰器的具体用法和示例:
#### 基本用法
当需要访问某个子组件或 DOM 元素时,可以使用 `ref` 属性定义引用,并通过 `@Ref` 将其映射到类的属性中。例如:
```typescript
<template>
<div>
<child-component ref="child"></child-component>
<button @click="handleClick">Click Me</button>
</div>
</template>
<script lang="ts">
import { Component, Ref, Vue } from 'vue-property-decorator';
import ChildComponent from './ChildComponent.vue';
@Component
export default class ParentComponent extends Vue {
@Ref('child') readonly childRef!: InstanceType<typeof ChildComponent>;
handleClick() {
if (this.childRef) {
console.log(this.childRef.someMethod());
}
}
}
</script>
```
在上述代码中,`@Ref('child')` 将模板中的 `ref="child"` 绑定到 `childRef` 属性上。通过这种方式,可以在方法中直接调用子组件的方法或访问其数据。
#### 类型推断与安全性
`@Ref` 支持类型推断,确保类型安全。如果未指定 `ref` 的名称,则默认使用装饰器修饰的属性名作为 `ref` 的键值。例如:
```typescript
<template>
<div>
<input ref="inputEl" type="text" />
</div>
</template>
<script lang="ts">
import { Component, Ref, Vue } from 'vue-property-decorator';
@Component
export default class InputExample extends Vue {
@Ref() readonly inputEl!: HTMLInputElement;
mounted() {
this.inputEl.focus();
}
}
</script>
```
在此示例中,`@Ref()` 自动将模板中的 `ref="inputEl"` 映射到 `inputEl` 属性上,并推断其类型为 `HTMLInputElement`。
#### 多个 Ref 的处理
如果一个 `ref` 名称对应多个元素(例如循环渲染的列表),可以通过 `@Ref` 获取一个数组类型的引用。例如:
```typescript
<template>
<ul>
<li v-for="(item, index) in items" :key="index" ref="listItems">{{ item }}</li>
</ul>
</template>
<script lang="ts">
import { Component, Ref, Vue } from 'vue-property-decorator';
@Component
export default class ListExample extends Vue {
items = ['Item 1', 'Item 2', 'Item 3'];
@Ref('listItems') readonly listItems!: HTMLLIElement[];
mounted() {
console.log(this.listItems.length); // 输出 3
}
}
</script>
```
在上述代码中,`@Ref('listItems')` 返回的是一个包含所有 `li` 元素的数组。
---
### 注意事项
- 如果 `ref` 对应的元素或组件不存在,则 `@Ref` 的值为 `undefined`。
- 在使用 `@Ref` 时,需确保目标元素或组件已在 DOM 中渲染完成(通常在 `mounted` 生命周期钩子之后)[^1]。
---
阅读全文
相关推荐


















