我正在尝试创建具有以下功能的 Web 组件:
1. 单击按钮以添加<textarea>
元素。
2. 给新建的<textarea>
元素添加文字后,该文字被添加到 的对应项中this.list
。
3. 在一个单独的脚本中能够获取 DOM 元素,document.querySelector()
然后从中检索数据this.list
。
这是我到目前为止所拥有的:
<!DOCTYPE html>
<html>
<body>
<my-element></my-element>
<script type="module">
import { LitElement, html } from "lit-element";
import { repeat } from "lit-html/directives/repeat.js";
class MyElement extends LitElement {
static get properties() {
return {
list: { type: Array },
};
}
constructor() {
super();
this.list = [
{ id: "1", text: "hello" },
{ id: "2", text: "hi" },
{ id: "3", text: "cool" },
];
}
render() {
return html`
${repeat(this.list, item => item.id,
item => html`<textarea>${item.text}</textarea>`
)}
<button @click="${this.addTextbox}">Add Textbox</button>
`;
}
addTextbox(event) {
const id = Math.random();
this.list = [...this.list, { id, text: "" }];
console.log(this.list); // text from new textboxes is not being added to list
}
}
customElements.define("my-element", MyElement);
</script>
<script>
const MyElement = document.querySelector("my-element");
const data = MyElement.properties; // undefined
</script>
</body>
</html>