Vue 3 Composition API-如何获取要在其上安装组件的组件元素($ el)

时间:2020-05-04 19:30:21

标签: vue.js vue-composition-api vuejs3

我想使用onMounted来启动第三方库。为此,我需要component元素作为其上下文。在Vue 2中,我将使用this.$el来实现它,但是不确定如何使用合成函数来实现它。 setup有两个参数,但都不包含元素。

setup(props, context) {
    onMounted(() => {
        interact($el)
            .resizable();
    })
}

2 个答案:

答案 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 的完整功能。