在 Vue 3 中,通过 ref 属性获取 DOM 元素或组件实例:添加 ref 属性,指定唯一名称。在组件中使用 useRef() 钩子创建引用,与 ref 属性绑定。通过 ref 属性访问 DOM 元素或组件实例,获取其值。
在 Vue 3 中,可以通过 ref 属性来获取 DOM 元素或组件实例。
获取一个按钮元素:
<template> <button ref="submitButton">提交</button> </template> <script> import { useRef } from 'vue'; export default { setup() { const submitButtonRef = useRef(); // 访问 DOM 元素 // ... return { submitButtonRef, }; }, }; </script>
获取一个组件实例:
<template> <CustomComponent ref="customComponent" /> </template> <script> import { useRef } from 'vue'; import CustomComponent from './CustomComponent.vue'; export default { setup() { const customComponentRef = useRef(); // 访问组件实例 // ... return { customComponentRef, }; }, }; </script>
一旦创建了引用,就可以通过 ref 属性访问 DOM 元素或组件实例:
立即学习“前端免费学习笔记(深入)”;
// 获取按钮元素 const submitButtonEl = this.submitButtonRef.value; // 获取组件实例 const customComponentInstance = this.customComponentRef.value;
在上述示例中,submitButtonEl 引用了按钮元素,customComponentInstance 引用了 CustomComponent 组件的实例。
以上就是vue3怎么获取dom的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号