【问题标题】:How to get this.$el of a component correctly, in Vue3?如何在 Vue3 中正确获取组件的 this.$el?
【发布时间】:2020-11-25 15:30:40
【问题描述】:

我有一个组件,它的模板是这样的:

<template>
  <slot />
</template>

我正在尝试制作的功能大约是resize-observer-polyfill。 我正在尝试在mounted() 中获取this.$el,然后创建ResizeObserver 的实例。

但问题是,如果 slot 的内容是async-component,那么我无法正确获取this.$el。

我该如何解决这个问题?

【问题讨论】:

    标签: vue.js vuejs3


    【解决方案1】:

    在 Vue 3 中,您可以使用 template ref:

    <template>
      <div ref="el"></div>
    </template>
    
    import { ref, onMounted } from 'vue'
    
    export default {
      setup() {
        const el = ref(null);
    
        // Not available until the component mounts:
        onMounted(() => {
          console.log(el.value)
        })
          
        return {
          el
        }
      } 
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-09-30
      • 1970-01-01
      • 2010-11-10
      • 2014-01-14
      • 2022-07-09
      • 2021-02-23
      • 2015-10-13
      • 2020-08-19
      相关资源
      最近更新 更多