【问题标题】:Attributes in Web Components do not show upWeb 组件中的属性不显示
【发布时间】:2020-09-10 23:33:34
【问题描述】:

这是我的带有自定义 Web 组件的 HTML。

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Advanced ToDo App with Web Components</title>
  </head>
  <body>
    <todo-item todo="Walk the dog" data-id="1"></todo-item>

    <script src="../static/listItems.js"></script>
  </body>
</html>

这是我设置组件的 JS 文件。

const template = document.createElement("template");

template.innerHTML = `<style>
h4 {
    color: white;
    font-size: 14px;
    display: block;
    padding: 10px 5px;
    background: orange;
}
</style>
<div class="todo-item">
    <h4></h4>
</div>
`;

class TodoItem extends HTMLElement {
  constructor() {
    super();

    this.attachShadow({ mode: "open" });
    this.shadowRoot.appendChild(template.content.cloneNode(true));
    this.shadowRoot.querySelector("h4").innerText = this.getAttribute("todo");
  }

  connectedCallback() {
    this.shadowRoot
      .querySelector(".todo-item")
      .addEventListener("click", () => {
        console.log(this.getAttribute("data-id"));
      });
  }
}

window.customElements.define("todo-item", TodoItem);

// Über Daten iterieren

const body = document.querySelector("body");

const dummydata = [
  { id: 1, description: "Walk the dog" },
  { id: 2, description: "Play football" }
];

for (item of dummydata) {
  console.log(item.description);
  todoItem = document.createElement("todo-item");
  todoItem.setAttribute("todo", item.description); # Does not work!
  todoItem.setAttribute("data-id", item.id);

  body.appendChild(todoItem);
}

HTML 中的组件工作得很好,但是当我尝试使用 JavaScript 设置动态创建它们时,属性似乎不起作用。 “待办事项”文本不会显示。设置这个“todo”属性无效吗?

【问题讨论】:

    标签: html components web-component


    【解决方案1】:

    知道了 - 必须在 connectedCallBack 函数中设置属性。在属性值为null之前执行此操作时@

      connectedCallback() {
        this.shadowRoot
          .querySelector(".todo-item")
          .addEventListener("click", () => {
            console.log(this.getAttribute("data-id"));
          });
        this.shadowRoot.querySelector("h4").innerText = this.getAttribute("todo");
      }
    

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-03-02
    • 2017-09-24
    • 1970-01-01
    • 1970-01-01
    • 2023-03-29
    • 2013-10-16
    • 1970-01-01
    相关资源
    最近更新 更多