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

Vue 3 中如何获取 DOM 元素
直接访问
-
$refs:Vue 的内置 API,允许直接使用 ref 属性访问 DOM 元素。
模板引用
-
...:在模板中使用 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 元素。
注意事项
- ref 的名称必须是唯一的。
- DOM 元素引用可能会在组件更新时更改。
- 建议在组件的
mounted生命周期钩子中获取 DOM 元素以确保其可用。
示例代码
Direct Access:
Template Reference:
...
export default {
mounted() {
console.log(this.$refs.myElement);
}
}Custom Directive:
Vue.directive('v-dom', {
bind(el, binding) {
binding.value(el);
}
});










