我想使用onMounted
来启动第三方库。为此,我需要component元素作为其上下文。在Vue 2中,我将使用this.$el
来实现它,但是不确定如何使用合成函数来实现它。 setup
有两个参数,但都不包含元素。
setup(props, context) {
onMounted(() => {
interact($el)
.resizable();
})
}
答案 0 :(得分:7)
tl; dr:
在Vue 3中,组件不再仅限于1个根元素。隐含地,这意味着您不再拥有$el
。
您必须使用ref
与模板中的任何元素进行交互。
如@AndrewSee在评论中所指出的那样,当使用渲染功能(不是模板)时,您可以在ref
选项中指定所需的createElement
:
render: function (createElement) {
return createElement('div', { ref: 'root' })
}
// or, in short form:
render: h => h('div', { ref: 'root' })
初始答案:
如docs中所述,
[...] 反应性引用和模板引用的概念在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>
中的一个根元素,因此您必须专门ref
为要与之交互的任何元素添加元素。
答案 1 :(得分:0)
您实际上可以在 Vue 3 Composition API 上使用 $el
。不过不推荐。
import { getCurrentInstance } from 'vue';
const el = getCurrentInstance().ctx.$el;
这似乎具有 Vue 2 上 $el 的完整功能。