我想用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 refstemplate 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>个元素中只有一个根元素,所以你必须明确地引用任何你想与之交互的元素.

Vue.js相关问答推荐

VUE:带自定义组件的数组输入绑定

Vuetify 2中自定义标头的排序和筛选

可组合数据获取示例

无法在cPanel/SSH上构建 | Laravel + Vue优化

VueJS3 - 在 for 循环中获取元素的句柄

Vue 和 Nuxt 之间生命周期钩子的不同行为

如何在 A-La-Carte 系统中使用 vuetify 加载程序时导入 vuetify/lib

Vue index.html favicon 问题

Vuex:如何等待动作完成?

为什么 vue 中的 @mouseover 操作不起作用

如何修复跨域读取阻塞 (CORB) 阻止了 MIME 类型应用程序/json 的跨域响应问题?

VueJS 通过渲染传递数据

如何在 Vue3 设置标签中定义组件名称?

基本 vue.js 2 和 vue-resource http 获取变量赋值

使用 Vue 在单个文件组件中调用渲染方法

Vue.js 单向绑定表单

Vue.js 中的 CSS 框架

无法访问函数内的数据属性

VueJS 复选框更新

如何在 Vue 数据对象中运行函数?