首页 > 解决方案 > 检测 DOM 中 Web 组件的安装

问题描述

我读了这个线程创建的网络组件:

<my-vue-web-comp [userId]="1" id="my-component"></my-vue-web-comp>

它在 Angular 中运行良好。如何检测 Web 组件何时安装在 DOM 中?

在这段代码中,我得到空值:

ngAfterViewInit() {
  const myComponent = document.getElementById('my-component')
  console.log(myComponent) //null
}

在这段代码中,我得到了我的组件,但我应该等待 0.5 秒:

ngAfterViewInit() {
        setTimeout(
            function() {
                const myComponent = document.getElementById('my-component')
                console.log(myComponent) //not null                
            }, 500)
    }

是否有任何工具(事件)来检测 DOM 中 Web 组件的安装?

标签: javascriptangulartypescriptvue.jsweb-component

解决方案


需要从文档中添加connectedCallback()

Vue.customElement('web-component', (MyWebComponent as any).options, { connectedCallback() {
      console.info('connectedCallback', this)
    }})

推荐阅读