vue2 中,我们可以在 mounted
钩子函数,通过 this.$el
获取到当前挂在的 dom 元素。然后用来初始化第三方插件,例如 echarts
例如下面例子
{
mounted() {
console.log(this.$el);
}
}
this 指向 vue 的实例,在脚手架中 this.$el
指向模板的根标签(用于获取 Vue 实例挂载的 Dom 元素),而且是在 mounted
生命周期里有效
vue3 获取挂载的 dom 元素
在 vue3 中,组件可以在 <tempale>
中有多个元素,而 vue2 只允许有一个元素,所以 $el
不只是指向当前元素,也就无法使用
我们可以这样实现
<template>
<div ref="root"></div>
</template>
<script>
import { ref, onMounted } from "vue";
export default {
setup() {
const root = ref(null);
onMounted(() => {
// 通过 root.value 来获取dom元素
console.log(root.value);
});
return {
root,
};
},
};
</script>
typescript版本
<script setup lang="ts">
import { ref, onMounted } from 'vue';
const root = ref<HTMLElement | null>(null);
onMounted(() => { console.log(root.value?.outerHTML) );
</script>
<template>
<div ref="root" />
</template>