
在 Nuxt 3 中,this.$refs 已被移除,但可通过 getCurrentInstance().refs 获取所有已注册的模板 ref,实现类似 Nuxt 2 的批量遍历逻辑,无需手动维护 ref 数组。
在 nuxt 3 中,`this.$refs` 已被移除,但可通过 `getcurrentinstance().refs` 获取所有已注册的模板 ref,实现类似 nuxt 2 的批量遍历逻辑,无需手动维护 ref 数组。
Nuxt 3 彻底拥抱 Composition API,摒弃了 Options API 中的 this 上下文,因此 this.$refs 不再可用。但 Vue 3 提供了底层机制——通过 getCurrentInstance() 访问当前组件实例,并从中读取 refs 对象(类型为 Record<string any></string>),它正是模板中所有 ref="xxx" 绑定的 DOM 元素或组件实例的集合,行为与 Nuxt 2 的 this.$refs 高度一致。
✅ 正确用法如下(需确保在 onMounted 或组件挂载后调用,因为 refs 在渲染完成前为空):
import { onMounted, getCurrentInstance } from 'vue'
onMounted(() => {
const instance = getCurrentInstance()
if (!instance) return
// 遍历所有模板 ref(key 为 ref 名,value 为对应元素/组件实例)
for (const [refKey, refValue] of Object.entries(instance.refs)) {
// 过滤出以 'inputValue' 开头的 ref(适配原逻辑)
if (refKey.startsWith('inputValue')) {
if (typeof refValue?.checkRequired === 'function') {
const message = refValue.checkRequired()
if (message?.result === false) {
error_message.push(message.message)
}
}
}
}
})
⚠️ 注意事项:
-
getCurrentInstance()仅在 setup 阶段或生命周期钩子中有效,不能在普通函数或异步回调中直接调用(可能返回null); - 模板中必须显式声明 ref,例如
<inputcomponent ref="inputValue0"></inputcomponent>或<input ref="inputValue1">; -
instance.refs是响应式对象,但其键值对本身不是响应式代理,因此不建议在watch中监听instance.refs的变化; - 若 ref 指向的是自定义组件,确保该组件暴露了
checkRequired方法(通过defineExpose);
? 更健壮的替代方案(推荐用于复杂场景):
若需更高可控性与类型安全,可结合 ref 数组 + v-for 动态绑定(配合 :ref 函数式 ref):
<template><div v-for="(item, i) in inputFields" :key="i">
<custominput :ref="el => { if (el) refs[i] = el }" :name="item.name"></custominput>
</div>
</template><script setup lang="ts">
import { ref, onMounted } from 'vue'
import CustomInput from './CustomInput.vue'
const inputFields = [
{ name: 'first_name' },
{ name: 'last_name' },
{ name: 'area_code' },
// ...
]
const refs = ref<(InstanceType<typeof CustomInput> | null)[]>([])
onMounted(() => {
refs.value.forEach((comp, i) => {
if (comp?.checkRequired) {
const msg = comp.checkRequired()
if (msg?.result === false) {
error_message.push(msg.message)
}
}
})
})
</script>
该方式完全规避 getCurrentInstance,类型更清晰,且天然支持动态增删字段。总结:优先使用 getCurrentInstance().refs 快速迁移旧逻辑;长期维护建议采用函数式 :ref + 数组管理,兼顾可读性、类型安全与扩展性。










