0

我正在尝试创建具有以下功能的 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>
4

1 回答 1

0

这是一个如何从 中检索数据的示例LitElement

演示

import { LitElement, html } from "lit-element";


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`

      ${this.list.map( item=> html`${item.id}. ${item.text}<br>`)}


     <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
    this.dispatchEvent(new CustomEvent('changed',{ bubles:true,composed:true, detail:{list:this.list}}));

  }

}
customElements.define("my-element", MyElement);

  const MyElement = document.querySelector("my-element");
  MyElement.addEventListener('changed',function(e){ 
    const list = e.detail.list;
    console.log('out->',list);

  });
于 2019-12-22T11:04:30.397 回答