Vue 3 中获取 DOM 元素的方式有六种:直接访问 $refs、模板引用、自定义指令 v-dom、事件处理程序 @event、Vue 事件总线 $emit 和 $on、获取组件 this.$children、this.$el。建议在组件的 mounted 生命周期钩子中获取 DOM 元素以确保其可用。

Vue 3 中如何获取 DOM 元素
直接访问
$refs:Vue 的内置 API,允许直接使用 ref 属性访问 DOM 元素。模板引用
<template ref="myRef">...</template>:在模板中使用 ref 指令为元素创建引用。然后使用 this.$refs.myRef 访问 DOM 元素。自定义指令
立即学习“前端免费学习笔记(深入)”;
v-dom 自定义指令:接受一个回调函数,该函数接收 DOM 元素作为参数。事件处理程序
@event 事件处理程序:可以使用 $event.target 访问 DOM 元素。Vue 事件总线
$emit 和 $on:可以发送和接收自定义事件,并在事件回调函数中访问 DOM 元素。获取组件
this.$children:存储当前组件的所有子组件,可以使用 $children[0].$el 获取其根 DOM 元素。this.$el:当前组件的根 DOM 元素。注意事项
mounted 生命周期钩子中获取 DOM 元素以确保其可用。示例代码
Direct Access:
<code class="js"><template>
<div ref="myElement"></div>
</template>
<script>
export default {
mounted() {
console.log(this.$refs.myElement);
}
}
</script></code>Template Reference:
<code class="html"><template ref="myElement">...</template></code>
<code class="js">export default {
mounted() {
console.log(this.$refs.myElement);
}
}</code>Custom Directive:
<code class="js">Vue.directive('v-dom', {
bind(el, binding) {
binding.value(el);
}
});</code><code class="html"><div v-dom="element => console.log(element)"></div></code>
以上就是vue3怎么获取dom元素的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号