什么是 ref
?
ref
是一个特殊的属性,当你添加它到一个Vue组件或原生DOM元素时,它会在 Vue 实例的 $refs
对象中创建一个引用,这样你就可以通过这个引用访问到该元素或组件。
如何使用 ref
?
1. 添加 ref
到组件或DOM元素
在模板中,你可以在任何组件或原生DOM元素上添加 ref
属性:
Html
1<template>
2 <div>
3 <input ref="myInput" type="text">
4 <my-component ref="myComponent"></my-component>
5 </div>
6</template>
这里,我们给一个输入框和一个自定义组件分别添加了 ref
属性。
2. 访问 $refs
对象
你可以在 Vue 实例的方法或计算属性中通过 this.$refs
访问这些带有 ref
的元素或组件:
Javascript
1export default {
2 methods: {
3 focusInput() {
4 this.$refs.myInput.focus(); // 调用 input 元素的 focus 方法
5 },
6 callComponentMethod() {
7 this.$refs.myComponent.someMethod(); // 调用 my-component 组件的一个方法
8 }
9 }
10}
注意事项
this.$refs
在 Vue 实例初始化完成之后才会可用。- 如果你尝试在生命周期钩子如
created
或者beforeMount
中访问$refs
,它们可能还不可用,因为这些钩子执行时 DOM 还未完全渲染完毕。因此,你应该在mounted
钩子或之后访问$refs
。 - 如果
ref
的值是一个组件,那么$refs
的值将是该组件的实例;如果ref
的值是一个普通的DOM元素,那么$refs
的值将是该DOM元素。
示例
假设你有以下Vue组件:
Html
深色版本
1<template>
2 <div>
3 <input ref="inputField" type="text">
4 <button @click="focusInput">Focus Input</button>
5 </div>
6</template>
7
8<script>
9export default {
10 methods: {
11 focusInput() {
12 this.$refs.inputField.focus();
13 }
14 }
15}
16</script>
在这个例子中,当你点击 "Focus Input" 按钮时,Vue 实例会调用 focusInput
方法,该方法通过 $refs.inputField
访问到 input 元素,并调用其 focus
方法使其获得焦点。