我想用onMounted
来启动第三方库.为此,我需要组件元素作为其上下文.在Vue 2中,我会用this.$el
获得它,但不确定如何使用合成函数.setup
有两个参数,但都不包含元素.
setup(props, context) {
onMounted(() => {
interact($el)
.resizable();
})
}
我想用onMounted
来启动第三方库.为此,我需要组件元素作为其上下文.在Vue 2中,我会用this.$el
获得它,但不确定如何使用合成函数.setup
有两个参数,但都不包含元素.
setup(props, context) {
onMounted(() => {
interact($el)
.resizable();
})
}
tl;dr:
In Vue 3, components are no longer limited at only 1 root element. Implicitly, this means you no longer have an $el
.
You have to use ref
to interact with any element in your template.
正如@AndrewSee在 comments 中指出的,当使用渲染函数(而不是模板)时,可以指定所需的createElement
个选项中的ref
个:
render: function (createElement) {
return createElement('div', { ref: 'root' })
}
// or, in short form:
render: h => h('div', { ref: 'root' })
initial answer:
如docs年所述,
[...] reactive refs和template refs的概念统一在Vue 3中.
还有一个例子,说明如何创建一个"根"元素.显然,你不需要把它命名为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>
个元素中只有一个根元素,所以你必须明确地引用任何你想与之交互的元素.