我正在学习 Web 组件,并正在构建一个动态列表来掌握它们。让它工作后,我读到最好使用该connectedCallback
方法附加影子根。但是,尝试这样做后,我得到了一堆我无法修复的错误。此外,我为标签设置简单属性的方式似乎有点冗长:是否有更简单的方法来获取属性并将其显示为标签?
这是我的工作示例:
const template = document.createElement('template');
template.innerHTML = `
<style>
:host {
display: block;
font-family: sans-serif;
text-align: center;
}
button {
border: none;
cursor: pointer;
}
ul {
list-style: none;
padding: 0;
}
</style>
<h1>To dos</h1>
<lable id="lable1"></lable>
<select></select>
`;
class TodoApp extends HTMLElement {
constructor() {
super();
this._shadowRoot = this.attachShadow({ 'mode': 'open' });
this._shadowRoot.appendChild(template.content.cloneNode(true));
this.$todoList = this._shadowRoot.querySelector('select');
this.label1 = this._shadowRoot.getElementById('lable1')
}
static get observedAttributes() {
return ['att1'];
}
attributeChangedCallback(name, oldValue, newValue) {
this.label1.innerText = this.getAttribute('att1');
}
renderTodoList() {
this.$todoList.innerHTML = '';
this.todosArray.forEach((todoP) => {
let $todoItem = document.createElement('option');
$todoItem.text = todoP.text;
$todoItem.value = todoP.id;
this.$todoList.appendChild($todoItem);
});
}
set todos(value) {
this.todosArray = value;
this.renderTodoList();
}
}
window.customElements.define('to-do-app', TodoApp);
当我添加一个connectedCallback()
方法并在那里创建 shadow dom 时,我得到了一堆错误。我的标记只是:
<to-do-app att1="value 1 attribute"></to-do-app>
我试过这个:
class TodoApp extends HTMLElement {
constructor() {
super();
this.label1 = '';
}
connectedCallback() {
this._shadowRoot = this.attachShadow({ 'mode': 'open' });
this._shadowRoot.appendChild(template.content.cloneNode(true));
this.$todoList = this._shadowRoot.querySelector('select');
this.label1 = this._shadowRoot.getElementById('lable1')
}
static get observedAttributes() {
return ['att1'];
}
attributeChangedCallback(name, oldValue, newValue) {
this.label1.innerText = this.getAttribute('att1');
}
但得到错误:
TypeError:无法分配给“”上的属性“innerText”:不是对象