Vue 3 模板引用(Template Refs)详解与实战示例

Vue 3 模板引用(Template Refs)详解与实战示例

引言

在 Vue 开发中,通常推荐使用 响应式数据 (refreactive) 进行数据绑定,而不是直接操作 DOM。但是,在某些情况下,我们确实需要访问某个组件或 DOM 元素,这时候就可以使用 模板引用(Template Refs)

本篇文章将详细介绍 Vue 3 的 ref 模板引用的用法、适用场景,并通过多个示例展示如何在 Vue 组件中高效操作 DOM 和组件实例。


1. 什么是 Vue 模板引用?

模板引用(Template Refs) 允许我们在 Vue 组件的模板中标记一个 DOM 元素或子组件,并在 setup 选项中访问它。

基本语法

html 复制代码
<template>
  <div ref="myDiv">Hello Vue!</div>
</template>

<script setup>
import { ref, onMounted } from 'vue';

const myDiv = ref(null); // 定义模板引用

onMounted(() => {
  console.log(myDiv.value); // 获取 DOM 元素
});
</script>

说明

  • ref="myDiv" 绑定到 myDiv 变量
  • onMounted 钩子确保 myDiv.value 在 DOM 渲染完成后可用

2. 模板引用的使用场景

✅ 操作原生 DOM

当我们需要手动操作 DOM 时,如获取元素的宽高、设置焦点等:

html 复制代码
<template>
  <input ref="inputRef" type="text" placeholder="输入内容">
  <button @click="focusInput">聚焦输入框</button>
</template>

<script setup>
import { ref } from 'vue';

const inputRef = ref(null);

const focusInput = () => {
  inputRef.value.focus(); // 手动聚焦输入框
};
</script>

✅ 获取子组件实例

可以使用 ref 访问子组件的方法和数据:

html 复制代码
<!-- 子组件 (Child.vue) -->
<template>
  <div>子组件</div>
</template>

<script setup>
import { ref } from 'vue';

const message = ref("Hello from Child Component!");

const sayHello = () => {
  console.log(message.value);
};

defineExpose({ sayHello }); // 允许父组件访问 `sayHello`
</script>
html 复制代码
<!-- 父组件 -->
<template>
  <Child ref="childRef" />
  <button @click="callChildMethod">调用子组件方法</button>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import Child from './Child.vue';

const childRef = ref(null);

onMounted(() => {
  console.log(childRef.value); // 获取子组件实例
});

const callChildMethod = () => {
  childRef.value.sayHello(); // 调用子组件方法
};
</script>

defineExpose :Vue 3 需要使用 defineExpose 公开组件方法,否则父组件无法访问。


3. 使用 ref 访问多个元素

当我们需要访问 多个 DOM 元素时,可以使用 ref 结合 v-for

html 复制代码
<template>
  <div v-for="(item, index) in list" :key="index" ref="itemRefs">
    {{ item }}
  </div>
  <button @click="logElements">查看所有元素</button>
</template>

<script setup>
import { ref, onMounted } from 'vue';

const list = ref(["Vue", "React", "Angular"]);
const itemRefs = ref([]); // 存储多个 DOM 元素

onMounted(() => {
  console.log(itemRefs.value); // 所有 div 的 DOM 元素
});

const logElements = () => {
  itemRefs.value.forEach(el => console.log(el.textContent));
};
</script>

注意ref 数组会在 onMounted 之后才填充值。


4. 访问 setup() 之外的数据

如果你在 setup() 之外使用 ref,可以通过 getCurrentInstance() 获取 Vue 实例:

html 复制代码
<script setup>
import { getCurrentInstance, onMounted } from 'vue';

onMounted(() => {
  const instance = getCurrentInstance();
  console.log(instance.refs); // 访问 ref
});
</script>

5. 结论

Vue 3 的 模板引用(Template Refs) 让我们可以更方便地访问 DOM 和子组件实例,适用于:

  • 操作原生 DOM(如获取焦点、测量元素尺寸)
  • 调用子组件方法 (通过 refdefineExpose
  • 获取多个元素 (使用 ref 数组)

但是 ,如果能用 Vue 的 响应式数据 来实现同样的效果,最好避免直接操作 DOM,以保持 Vue 响应式系统的优势。

相关推荐
渔舟唱晚@7 分钟前
大模型数据流处理实战:Vue+NDJSON的Markdown安全渲染架构
vue.js·大模型·数据流
crary,记忆37 分钟前
Angular微前端架构:Module Federation + ngx-build-plus (Webpack)
前端·webpack·angular·angular.js
漂流瓶jz1 小时前
让数据"流动"起来!Node.js实现流式渲染/流式传输与背后的HTTP原理
前端·javascript·node.js
SamHou01 小时前
手把手 CSS 盒子模型——从零开始的奶奶级 Web 开发教程2
前端·css·web
我不吃饼干2 小时前
从 Vue3 源码中了解你所不知道的 never
前端·typescript
开航母的李大2 小时前
【中间件】Web服务、消息队列、缓存与微服务治理:Nginx、Kafka、Redis、Nacos 详解
前端·redis·nginx·缓存·微服务·kafka
Bruk.Liu2 小时前
《Minio 分片上传实现(基于Spring Boot)》
前端·spring boot·minio
鱼樱前端2 小时前
Vue3+d3-cloud+d3-scale+d3-scale-chromatic实现词云组件
前端·javascript·vue.js
q_19132846952 小时前
基于Springboot+Vue的办公管理系统
java·vue.js·spring boot·后端·intellij idea
coding随想2 小时前
JavaScript中的原始值包装类型:让基本类型也能“变身”对象
开发语言·javascript·ecmascript