我什么时候应该在constructor
或connectedCallback
中应用模板?当我在回调中执行此操作时,有时会在之前调用attributeChangedCallback
并且我无法查询元素。
export class TestElement extends HTMLElement {
constructor() {
super();
//here ?
}
connectedCallback() {
//here ?
}
}
我想知道在哪里以及为什么更好。
这是模板应用代码的截图
let t = document.createElement('template');
t.innerHTML = require('template.html');
this.appendChild(t.content.cloneNode(true));
如果不使用 Shadow DOM,则不应在constructor()
回调中插入模板。
因此,您应该仅将其附加到 connectedCallback()
中。
无论如何,attributeChangedCallback()
可以在上述回调之前或之后调用,具体取决于自定义元素的使用方式。因此,在尝试查询某些内部元素之前,您应该始终进行测试。