获取模板后 QuerySelector 不工作 - WebComponents

QuerySelector not working after fetching template - WebComponents

TeleMenu 有两个按钮,我正试图抓住它们,但是 this.shadowRoot.querySelector 有问题。

错误:

Uncaught (in promise) TypeError: Cannot read property 'querySelector' of null

代码:

class TeleMenu extends HTMLElement {

buttons = [];

constructor() {
    super();

    fetch('tele-menu.html')
        .then(resp => resp.text())
        .then(resp => {
            this.attachShadow({ mode: 'open' })
                .innerHTML = resp
        })

    this.buttons = Array.from(this.shadowRoot.querySelectorAll('button'));
}

你能帮忙吗?

谢谢

fetch 是异步的,您正在执行 .querySelectorAll long before innerHTML 设置

constructor() {
    super();

    fetch('tele-menu.html')
        .then(resp => resp.text())
        .then(resp => {
            this.attachShadow({ mode: 'open' })
                .innerHTML = resp
        })

    this.buttons = Array.from(this.shadowRoot.querySelectorAll('button'));
}

Google 和 MDN 文档错误 运行 super() first

super() 设置并创建 'this' 范围。

所以你不能在 super 有 运行 之前调用 this.. 这是唯一的限制

你可以这样做:

constructor() {
    fetch('tele-menu.html')
        .then(resp => resp.text())
        .then(resp => {
            super().attachShadow({ mode: 'open' })
                   .innerHTML = resp;
            this.buttons = [...this.shadowRoot.querySelectorAll('button')];//modern way
            // do more here
        })
}

https://javascript.info/async-await 可能有助于保持您的代码更简洁