在 Vue 3 中,通过 ref 属性获取 DOM 元素或组件实例:添加 ref 属性,指定唯一名称。在组件中使用 useRef() 钩子创建引用,与 ref 属性绑定。通过 ref 属性访问 DOM 元素或组件实例,获取其值。

Vue 3 中如何获取 DOM
在 Vue 3 中,可以通过 ref 属性来获取 DOM 元素或组件实例。
步骤:
-
向模板添加
ref属性: 为需要获取的 DOM 元素或组件添加ref属性,并指定一个唯一的名称。 -
在组件中使用
ref: 在组件的setup()方法中,使用useRef()钩子创建引用,并将其与ref属性绑定的名称关联。
示例:
获取一个按钮元素:
获取一个组件实例:
访问 DOM 元素或组件实例
一旦创建了引用,就可以通过 ref 属性访问 DOM 元素或组件实例:
立即学习“前端免费学习笔记(深入)”;
// 获取按钮元素 const submitButtonEl = this.submitButtonRef.value; // 获取组件实例 const customComponentInstance = this.customComponentRef.value;
在上述示例中,submitButtonEl 引用了按钮元素,customComponentInstance 引用了 CustomComponent 组件的实例。










