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