在 Vue 中,获取 DOM 元素有三种方法:1. 使用 ref 属性为元素指定引用变量,并通过 this.$refs 访问;2. 直接使用组件的根元素 this.$el;3. 使用 querySelector 方法在绑定元素上查询。
在 Vue 中获取 DOM 元素
在 Vue 应用中,可以通过以下方法获取 DOM 元素:
1. ref 属性
<template> <div ref="myDiv"></div> </template> <script> import { ref } from 'vue' export default { setup() { const myDiv = ref(null) // 声明一个空引用变量 return { myDiv } }, mounted() { console.log(this.$refs.myDiv) // myDiv 元素 } } </script>
2. $el 属性
立即学习“前端免费学习笔记(深入)”;
<template> <div></div> </template> <script> import { ref } from 'vue' export default { setup() { const myDiv = ref(null) // 声明一个空引用变量 return { myDiv } }, mounted() { console.log(this.$el) // 组件的根元素 } } </script>
3. querySelector
<template> <div></div> </template> <script> import { ref } from 'vue' export default { setup() { // 绑定一个空引用变量 const myDiv = ref(null) return { myDiv } }, mounted() { this.myDiv.value = this.$el.querySelector('div') } } </script>
以上就是vue中怎么获取dom元素的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号