Vue 3组合式API中如何使用动态ref?
Vue 3组合式API实现动态Ref(无需模板ref函数)
方案1:利用组件实例的refs(兼容所有Vue3版本)
- 模板中绑定动态字符串ref
和选项式API的写法一致,通过:ref绑定动态生成的字符串名称:
<template> <div v-for="(item, index) in 5" :key="index" :ref="`name${index}`"> 元素{{ index }} </div> </template>
- 组合式API中访问动态ref
通过getCurrentInstance()获取当前组件实例,再通过instance.refs访问所有模板ref:
<script setup> import { getCurrentInstance, onMounted } from 'vue' const instance = getCurrentInstance() onMounted(() => { // 访问单个动态ref const firstElement = instance.refs.name0 console.log(firstElement.textContent) // 输出:元素0 // 遍历所有动态ref for (let i = 0; i < 5; i++) { console.log(instance.refs[`name${i}`]) } }) </script>
注意:
getCurrentInstance()仅能在setup函数或生命周期钩子内调用,官方不推荐在生产代码中过度依赖组件实例,但这是实现需求的直接方式。
方案2:Vue3.3+推荐方式(使用useTemplateRefs)
Vue3.3新增的useTemplateRefs()工具函数,能更优雅地管理模板ref集合:
- 模板绑定动态ref
保持和方案1一致的模板写法:
<template> <div v-for="(item, index) in 5" :key="index" :ref="`name${index}`"> 元素{{ index }} </div> </template>
- 通过
useTemplateRefs访问
<script setup> import { useTemplateRefs, onMounted } from 'vue' const refs = useTemplateRefs() onMounted(() => { console.log(refs.name0.textContent) // 输出:元素0 console.log(refs['name1']) // 获取第二个元素DOM节点 }) </script>
这种方式无需直接操作组件实例,更贴合组合式API的设计风格。
关键注意事项
- 动态ref仅在组件挂载完成后才能获取到有效引用,必须在
onMounted或后续生命周期钩子中操作。 - 当循环列表更新时,
refs集合会自动同步最新的元素引用,无需手动维护。
内容的提问来源于stack exchange,提问作者Liel
相关产品推荐
相关产品推荐

