Vue 模板引用
封面图
•
2025-11-16
•
Vue
0
0
0
0
在 Vue 中,**模板引用(Template Refs)** 是一种通过 `ref` 属性来获取 DOM 元素或组件实例的方法。它在 Vue 2 和 Vue 3 中都支持,但在 Vue 3 中有一些改进。 --- ## ✅ 一、基本用法 ### 1. 引用 DOM 元素 ```vue <template> <div> <input ref="inputRef" type="text" placeholder="请输入内容"> <button @click="focusInput">聚焦输入框</button> </div> </template> <script> export default { methods: { focusInput() { this.$refs.inputRef.focus(); // 调用 DOM 方法 } } } </script> ``` > 在 Vue 3 中,`this.$refs` 仍然可用,但推荐使用 Composition API 的 `ref`。 --- ### 2. 引用子组件 ```vue <template> <div> <ChildComponent ref="childRef" /> <button @click="callChildMethod">调用子组件方法</button> </div> </template> <script> import ChildComponent from './ChildComponent.vue' export default { components: { ChildComponent }, methods: { callChildMethod() { this.$refs.childRef.childMethod(); // 调用子组件的方法 } } } </script> ``` --- ## ✅ 二、Vue 3 中的 `ref`(Composition API) 如果你使用的是 Vue 3 的 **Composition API**,可以这样使用: ```vue <template> <div> <input ref="inputRef" type="text" placeholder="请输入内容"> <button @click="focusInput">聚焦输入框</button> </div> </template> <script setup> import { ref } from 'vue'; const inputRef = ref(null); function focusInput() { inputRef.value.focus(); } </script> ``` > 这里 `ref` 是一个响应式对象,需要通过 `.value` 来访问 DOM 或组件实例。 --- ## ✅ 三、注意事项 | 特性 | 说明 | |------|------| | `ref` 只能在模板中声明 | 不能在 JS 中直接定义 `ref` | | `ref` 是响应式的 | 在 Vue 3 中,`ref` 是响应式的,但 `this.$refs` 不是 | | `ref` 会指向组件实例或 DOM 元素 | 根据你引用的是组件还是元素而定 | | 不要滥用 `ref` | 它主要用于需要直接操作 DOM 或组件的情况,应尽量避免过度使用 | --- ## ✅ 四、常见问题 ### ❓为什么 `this.$refs` 为 `null`? - 组件尚未渲染完成(例如在 `created` 钩子中访问) - `ref` 没有正确绑定到元素或组件 - 使用了 `v-if` 控制显示,但未等待条件为真 --- ## ✅ 五、总结 | 场景 | 用法 | |------|------| | 引用 DOM 元素 | `<input ref="inputRef">` | | 引用子组件 | `<ChildComponent ref="childRef" />` | | Vue 3 (Options API) | `this.$refs.xxx` | | Vue 3 (Composition API) | `const refName = ref(null)`,然后通过 `.value` 访问 | --- 如果你有具体的使用场景(比如引用组件、动态组件、表单验证等),我可以提供更详细的示例!
上一篇:
Vue 表单输入绑定
标题录入,一次不能超过6条
留言
评论