亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

通過 createElement 創建 WebComponent

通過 createElement 創建 WebComponent

三國紛爭 2022-12-02 10:36:53
我在使用 createElement 創建 Web 組件時遇到問題。我收到此錯誤:未捕獲的 DOMException:無法構造“CustomElement”:結果在 appendTodo 中不能有子項class TodoCard extends HTMLElement {    constructor() {        super()        this.innerHTML = `            <li>                <div class="card">                    <span class="card-content">${this.getAttribute('content')}</span>                    <i class="fa fa-circle-o" aria-hidden="true"></i>                    <i class="fa fa-star-o" aria-hidden="true"></i>                </div>            </li>        `    }}window.customElements.define('todo-card', TodoCard)const todoList = document.getElementById('todo-list')const todoForm = document.getElementById('todo-form')const todoInput = document.getElementById('todo-input')function appendTodo(content) {    const todo = document.createElement('todo-card')    todo.setAttribute('content', content)    todoList.appendChild(todo)}todoForm.addEventListener('submit', e => {    e.preventDefault()    appendTodo(todoInput.value)    todoInput.value = ''})有任何想法嗎?謝謝。
查看完整描述

1 回答

?
慕田峪9158850

TA貢獻1794條經驗 獲得超7個贊

constructor

永遠無法創建在中設置 DOM 內容的自定義元素document.createElement()


您將看到許多示例(包括我的示例),其中 DOM 內容是在構造函數中設置的。

這些元素永遠無法創建document.createElement


說明(HTML DOM API):

當您使用時:


  <todo-card content=FOO></todo-card>

該元素(從 HTMLElement 擴展)具有所有 HTML 接口(它在 HTML DOM 中),

您可以在構造函數中設置 innerHTML


但是,當你這樣做時:


  document.createElement("todo-card");

構造函數在沒有 HTML 接口的情況下運行(元素可能與 DOM 無關),因此在構造函數

中設置 innerHTML會產生錯誤:


未捕獲的 DOMException:無法構造“CustomElement”:結果不得有子項


來自https://html.spec.whatwg.org/multipage/custom-elements.html#custom-element-conformance:


該元素不得獲得任何屬性或子元素,因為這違反了使用 createElement 或 createElementNS 方法的消費者的期望。一般來說,工作應該盡可能推遲到 connectedCallback


shadowDOM 是一個 DOM

使用shadowDOM時,您可以在構造函數中設置shadowDOM內容:


  constructor(){

    super().attachShadow({mode:"open"})

           .innerHTML = `...`;

  }

正確的代碼(沒有 shadowDOM):使用connectedCallback:

<todo-card content=FOO></todo-card>


<script>

  window.customElements.define(

    "todo-card",

    class extends HTMLElement {

      constructor() {

        super();

        //this.innerHTML = this.getAttribute("content");

      }

      connectedCallback() {

        this.innerHTML = this.getAttribute("content");

      }

    }

  );


  try {

    const todo = document.createElement("todo-card");

    todo.setAttribute("content", "BAR");

    document.body.appendChild(todo);

  } catch (e) {

    console.error(e);

  }

</script>

您還有另一個小問題:content 默認屬性,FireFox 不會停止警告您:

http://img1.sycdn.imooc.com//638964ee0001f6fa05700020.jpg

或者不使用 createElement

  const todo = document.createElement("todo-card");

  todo.setAttribute("content", "BAR");

  document.body.appendChild(todo);

可以寫成:


  const html = `<todo-card content="BAR"></todo-card`;

  document.body.insertAdjacentHTML("beforeend" , html); 

可以connectedCallback運行多次!

當你四處移動 DOM 節點時:


<div id=DO_Learn>

  <b>DO Learn: </b><todo-card todo="Custom Elements API"></todo-card>

</div>

<div id="DONT_Learn">

  <b>DON'T Learn!!! </b><todo-card todo="React"></todo-card>

</div>

<script>

  window.customElements.define(

    "todo-card",

    class extends HTMLElement {

      connectedCallback() {

        let txt = this.getAttribute("todo");

        this.append(txt);// and appended again on DOM moves

        console.log("qqmp connectedCallback\t", this.parentNode.id, this.innerHTML);

      }

      disconnectedCallback() {

        console.log("disconnectedCallback\t", this.parentNode.id , this.innerHTML);

      }

    }

  );

  const LIT = document.createElement("todo-card");

  LIT.setAttribute("todo", "Lit");

  DO_Learn.append(LIT);

  DONT_Learn.append(LIT);

</script>

  • LIT 的 connectedCallback 運行

  • 移動 LIT 時

  • disconnectedCallback 運行(注意父級!元素已經在新位置)

  • LIT 的 connectedCallback 再次運行,再次"Learn Lit" 追加

這取決于你的程序員你的組件/應用程序必須如何處理這個

Web 組件庫

像 Lit、HyperHTML 和 Hybrids 這樣的庫實現了額外的回調來幫助解決所有這些問題。

我建議先學習自定義元素 API,否則你學習的是工具而不是技術。

有工具的傻瓜,仍然是傻瓜


查看完整回答
反對 回復 2022-12-02
  • 1 回答
  • 0 關注
  • 160 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號