【问题标题】:Detect mounting of web-component in DOM检测 DOM 中 Web 组件的安装
【发布时间】:2021-10-30 07:23:57
【问题描述】:

我读到了这个thread 创建的网络组件:

<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 组件的安装?

【问题讨论】:

  • 我猜你的 web 组件可以简单地在顶级元素上触发一个 customEvent ?你的 Angular 应用可以监听那个事件。
  • @MikeOne 是的,我可以从我的网络组件中调用该函数,但是如何检测它何时安装在 Angular 的网络应用程序 DOM 中?
  • 恕我直言,您学习 Web 组件的顺序错误。您现在首先学习工具语法,然后再学习核心技术。我的建议是,首先学习开发(基本的)vanilla JavaScript Web Components。之后选择一个工具来加速开发。

标签: javascript angular typescript vue.js web-component


【解决方案1】:

需要从docs添加connectedCallback()

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-03-14
    • 1970-01-01
    • 1970-01-01
    • 2017-10-27
    • 2021-12-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多