tl;博士:
在 Vue 3 中,组件不再仅限于 1 个根元素。隐含地,这意味着您不再拥有$el。
您必须使用 ref 与模板中的任何元素进行交互。
正如@AndrewSee 在 cmets 中指出的,当使用渲染函数(不是模板)时,您可以在 createElement 选项中指定所需的 ref:
render: function (createElement) {
return createElement('div', { ref: 'root' })
}
// or, in short form:
render: h => h('div', { ref: 'root' })
初步答案:
如docs 中所述,
[...] reactive refs 和 template refs 的概念在 Vue 3 中是统一的。
您还有一个关于如何ref“根”元素的示例。显然,您不需要将其命名为 root。如果您愿意,可以将其命名为 $el。但是,这样做并不意味着它将以this.$el 的形式提供,而是以this.$refs.$el 的形式提供。
<template>
<div ref="root"></div>
</template>
<script>
import { ref, onMounted } from 'vue'
export default {
setup() {
const root = ref(null)
onMounted(() => {
// the DOM element will be assigned to the ref after initial render
console.log(root.value) // this is your $el
})
return {
root
}
}
}
</script>
在 Vue 3 中,您不再仅限于 <template> 中的一个根元素,因此您必须专门reference 任何要与之交互的元素。