Vue $refs
在 Vue 中,我们可以使用 $refs 来访问组件或者 DOM 元素。
使用 $refs 访问组件
在 Vue 中,如果想要访问子组件的方法或者属性,可以使用 $refs,首先在父组件中通过 ref 属性给子组件命名,然后就可以通过 $refs 来访问该子组件了。
例如,我们有一个子组件 ChildComponent,它有一个方法 childMethod(),我们想在父组件中调用该方法,可以这样做:
复制代码
<template>
<div>
<child-component ref="child"></child-component>
<button @click="callChildMethod()">调用子组件方法</button>
</div>
</template>
<script>
import ChildComponent from '@/components/ChildComponent.vue';
export default {
components: { ChildComponent },
methods: {
callChildMethod() {
this.$refs.child.childMethod();
}
}
}
</script>
这里我们在子组件上使用 ref 属性来为其命名,并将其赋值给 this.$refs 对象,然后我们就可以通过 this.$refs.child 来访问该子组件的方法 childMethod() 了。
使用 $refs 访问 DOM 元素
除了可以访问组件,我们还可以使用 $refs 来访问 DOM 元素。
例如,在 Vue 中我们想要让一个按钮被点击时自动获取焦点,可以这样实现:
复制代码
<template>
<div>
<button ref="myBtn" @click="focusMyBtn()">点击获取焦点</button>
</div>
</template>
<script>
export default {
methods: {
focusMyBtn() {
this.$refs.myBtn.focus();
}
}
}
</script>
这里我们在按钮上使用 ref 属性来为其命名,并将其赋值给 this.$refs 对象,然后我们就可以通过 this.$refs.myBtn 来访问该按钮了,从而调用其 focus() 方法来使其获得焦点。
总之,在 Vue 中,使用 $refs 可以让我们轻松地访问子组件或者 DOM 元素的方法或属性,是一个非常方便的功能。