javascript - ตรวจจับการติดตั้งของเว็บคอมโพเนนต์ใน DOM
ฉันอ่านกระทู้นี้ที่สร้าง web-component:
<my-vue-web-comp [userId]="1" id="my-component"></my-vue-web-comp>
มันทำงานได้ดีใน Angular ฉันจะตรวจสอบได้อย่างไรว่าคอมโพเนนต์เว็บถูกติดตั้งใน DOM แล้ว
ในโค้ดนี้ฉันได้ค่าเป็น null:
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?
คำตอบ #1
ต้องเพิ่ม connectedCallback() จากเอกสาร:
Vue.customElement('web-component', (MyWebComponent as any).options, { connectedCallback() {
console.info('connectedCallback', this)
}})
