【问题标题】:How to handle click event and append HTML in Lit-Element?如何处理点击事件并在 Lit-Element 中附加 HTML?
【发布时间】:2021-11-15 14:12:59
【问题描述】:
  • 尝试使用每个按钮单击来创建一个列表。

  • 我想在 ul 元素中附加 li 标签。 OnClick 我已经创建了 addList 函数。

  • 处理点击事件。

    这里是代码。

render() {
    return html`
    <input oninput="${this.getNewVal}" id="name" type="text" value="${this.name}">
    <button onclick="${this._addList}" type="button">Add</button>
    <p class=${classMap(this.classes)} style=${styleMap(this.styles)}>Hello, ${this.name}!</p>
    <ul></ul>
    `;
  }

function addList(){
    this.listItems.push(this.name);
}

【问题讨论】:

  • Hiten,为了更好地理解您的查询或错误,请分享您的代码。

标签: polymer web-component lit-element lit


【解决方案1】:

你基本上需要做的是:

  1. 拥有一个存储列表项的数组
  2. 单击按钮时向所述数组添加新元素
  3. 使用 repeat 指令的数组的 map 函数呈现列表(取决于您是否要对所述项目重新排序,其中一个可能比另一个更有效)

这是一个示例(取自lit.dev tutorial

import {LitElement, html} from 'lit';

class ToDoList extends LitElement {
  static properties = {
    listItems: {},
  };

  constructor() {
    super();
    this.listItems = [
      {text: 'Start Lit tutorial', completed: true},
      {text: 'Make to-do list', completed: false},
    ];
  }

  render() {
    return html`
      <h2>To Do</h2>
      <ul>
        ${this.listItems.map((item) => html`<li>${item.text}</li>`)}
      </ul>
      <input id="newitem" aria-label="New item">
      <button @click=${this.addToDo}>Add</button>
    `;
  }

  get input() {
    return this.renderRoot?.querySelector('#newitem') ?? null;
  }

  addToDo() {
    this.listItems.push({text: this.input.value, completed: false});
    this.input.value = '';
    this.requestUpdate();
  }
}
customElements.define('todo-list', ToDoList);

您可能想查看 lit 文档的 the template section 或者只是执行我上面提到的 tutorial

【讨论】:

    猜你喜欢
    • 2021-04-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-09-13
    • 1970-01-01
    • 1970-01-01
    • 2019-11-15
    相关资源
    最近更新 更多