
Nuxt 3 废弃了 Vue 2 的 this.$refs,但可通过 getCurrentInstance().refs 在 onMounted 中安全访问所有已注册的模板 ref,实现类似 Vue 2 的批量操作逻辑。
nuxt 3 废弃了 vue 2 的 `this.$refs`,但可通过 `getcurrentinstance().refs` 在 `onmounted` 中安全访问所有已注册的模板 ref,实现类似 vue 2 的批量操作逻辑。
在 Nuxt 3(基于 Vue 3 Composition API)中,ref 不再通过 this 访问,也无法像 Vue 2 那样用字符串动态拼接 this.$refs['inputValue' + i]。但 Vue 3 内部仍维护着一个 refs 对象,可通过 getCurrentInstance().refs 获取——注意:该 API 属于 Vue 内部实例(ComponentInternalInstance),仅在组件已挂载、且存在有效实例时可用,因此必须在 onMounted 或生命周期钩子中调用。
✅ 正确用法:获取并遍历所有模板 ref
import { onMounted, getCurrentInstance } from 'vue'
onMounted(() => {
const instance = getCurrentInstance()
if (!instance) return
// 获取所有通过 ref="xxx" 绑定的 DOM 元素或组件实例
const refs = instance.refs
// 遍历所有 ref(key 为 ref 名,value 为绑定的元素/组件实例)
for (const [key, refValue] of Object.entries(refs)) {
// 过滤出以 'inputValue' 开头的 ref(按需匹配)
if (typeof key === 'string' && key.startsWith('inputValue')) {
// 假设每个 ref 指向一个具有 checkRequired() 方法的自定义组件
if (typeof (refValue as any)?.checkRequired === 'function') {
const result = (refValue as any).checkRequired()
if (!result?.result) {
error_message.push(result.message)
}
}
}
}
})
⚠️ 注意事项
-
getCurrentInstance()返回值可能为null:仅在 setup 执行期间及组件挂载后有效,务必在onMounted中使用,并做空值校验; -
refs是响应式对象,但其属性本身不响应式:它仅在模板中ref="xxx"绑定完成时一次性填充,不会随后续 ref 动态增删而更新; -
避免在模板中重复使用相同 ref 名:Vue 会将同名 ref 自动转为数组(如多个
<input ref="item">→refs.item为Array),需额外判断类型; -
类型安全建议:
getCurrentInstance().refs类型为Record<string any></string>,可配合 TypeScript 接口或类型断言增强可读性,例如:interface FormRefs { first_name_ref: InstanceType<typeof inputfield> | null inputValue0: InstanceType<typeof custominput> | null // …… } const refs = instance.refs as FormRefs</typeof></typeof>
✅ 更优雅的替代方案(推荐)
若 ref 数量固定且语义明确,建议改用 ref 数组 + v-for + ref 函数式绑定,兼顾可维护性与类型安全:
<template><custominput v-for="(field, index) in fields" :key="field.id" :ref="(el) => { inputRefs[index] = el }" :label="field.label"></custominput></template><script setup lang="ts">
import { ref, onMounted } from 'vue'
import type { InstanceType } from 'vue'
const fields = [
{ id: 'first', label: 'First Name' },
{ id: 'last', label: 'Last Name' },
{ id: 'phone', label: 'Phone Number' }
]
const inputRefs = ref<(InstanceType<typeof CustomInput> | null)[]>([])
onMounted(() => {
inputRefs.value.forEach((comp) => {
if (comp?.checkRequired) {
const res = comp.checkRequired()
if (!res.result) error_message.push(res.message)
}
})
})
</script>
这种方式无需依赖内部 API,完全符合 Composition API 设计哲学,扩展性强,且天然支持 TypeScript 类型推导。
总之,getCurrentInstance().refs 是兼容旧逻辑的快捷入口,但长期项目建议转向函数式 ref 绑定 + 数组管理,更健壮、更易测试、更易维护。










