Vue.js 中 $refs 的使用指南
在 Vue 中,可以使用 $refs 来访问组件或元素。$refs 是一个对象,其属性是通过 ref 指令命名的元素或组件的名称,值是对应的元素或组件实例。
以下是 $refs 的使用方法:
- 在模板中使用 ref 指令给元素或组件命名:
<template>
<div>
<input type='text' ref='input'>
<my-component ref='myComponent'></my-component>
</div>
</template>
- 在组件实例中使用 $refs 访问元素或组件实例:
<script>
export default {
mounted() {
// 访问 input 元素
this.$refs.input.focus();
// 访问 my-component 组件实例
this.$refs.myComponent.doSomething();
}
}
</script>
注意,$refs 仅在组件渲染完成后才会填充,因此在组件的 created 或 beforeMount 钩子中访问 $refs 会返回 undefined。
原文地址: https://www.cveoy.top/t/topic/jozP 著作权归作者所有。请勿转载和采集!