从LitElement Web组件检索属性数据

时间:2019-12-21 18:43:12

标签: javascript web-component lit-element native-web-component

我正在尝试创建具有以下功能的Web组件:
1.单击按钮以添加<textarea>元素。
2.在将文本添加到新创建的<textarea>元素之后,此文本将添加到this.list的相应项目中。
3.在单独的脚本中,可以使用document.querySelector()获取DOM元素,然后从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>

1 个答案:

答案 0 :(得分:0)

下面是一个如何从LitElement检索数据的示例;

Demo

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);

  });