Vue 3 Composition API - 如何获取安装组件的组件元素($el) [英] Vue 3 Composition API - How to get the component element ($el) on which component is mounted

查看:498
本文介绍了Vue 3 Composition API - 如何获取安装组件的组件元素($el)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用onMounted 来启动第三方库.为此,我需要组件元素作为其上下文.在 Vue 2 中,我会使用 this.$el 获得它,但不确定如何使用组合函数来实现.setup 有两个参数,没有一个包含元素.

I want to use onMounted to initiate third-party library. To do that I need the component element as its context. In Vue 2 I would get it with this.$el but not sure how to do it with composition functions. setup has two arguments and none of them contains the element.

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

推荐答案

tl;dr:

在 Vue 3 中,组件不再仅限于 1 个根元素.隐含地,这意味着您不再拥有 $el.
您必须使用 ref 与模板中的任何元素进行交互.

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 在评论中指出的那样,当使用渲染函数(不是模板)时,您可以在 createElement 选项中指定所需的 ref:

As pointed out by @AndrewSee in comments, when using a render function (not a template), you can specify the desired ref in createElement options:

render: function (createElement) {
  return createElement('div', { ref: 'root' })
}
// or, in short form:
render: h => h('div', { ref: 'root' })


初始答案:

文档中所述,

[...] reactive refstemplate refs 的概念在 Vue 3 中是统一的.

[...] the concepts of reactive refs and template refs are unified in Vue 3.

您还有一个关于如何refroot"的示例.元素.显然,您不需要将其命名为 root.如果您愿意,将其命名为 $el.但是,这样做并不意味着它可以作为 this.$el 使用,而是作为 this.$refs.$el.

And you also have an example on how to ref a "root" element. Obviously, you don't need to name it root. Name it $el, if you prefer. However, doing so doesn't mean it will be available as this.$el, but as 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 中,您不再局限于