【问题标题】:Vue 3 Composition API - How to get the component element ($el) on which component is mountedVue 3 Composition API - 如何获取安装组件的组件元素($el)
【发布时间】:2020-08-19 08:13:26
【问题描述】:

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

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

【问题讨论】:

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


    【解决方案1】:

    tl;博士:

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

    正如@AndrewSee 在 cmets 中指出的,当使用渲染函数(不是模板)时,您可以在 createElement 选项中指定所需的 ref

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

    初步答案:

    docs 中所述,

    [...] reactive refstemplate refs 的概念在 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 中,您不再仅限于 &lt;template&gt; 中的一个根元素,因此您必须专门reference 任何要与之交互的元素。

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-11-29
    • 2023-01-10
    • 2021-10-24
    • 2016-08-02
    • 1970-01-01
    • 2018-04-21
    • 2021-06-24
    • 2021-08-15
    相关资源
    最近更新 更多