簡體   English   中英

有沒有辦法向自定義元素添加自定義屬性

[英]Is there a way to add custom attributes to custom elements

在擺弄自定義元素時,我想知道是否可以在元素中(也可能在它們的子元素中)使用自定義屬性。 我知道 VueJS 對 v-bind、v-for 等屬性做了類似的事情; 而且我知道在幕后發生的事情可能比我意識到的要多得多。 我試過注冊自定義元素並嘗試像這樣檢索它們:

<new-element cool="Awesome!"> </new-element>

class NewElement extends HTMLElement {
    constructor() {
        super();
        this.coolAttr = this.getAttribute("cool");
    }
}

customElements.define("new-element", NewElement);

但是,當加載頁面時(在我的谷歌瀏覽器中),“自定義”屬性消失了,任何獲取它們的嘗試都會檢索到 null。有沒有辦法“注冊”這些自定義屬性,或者我必須堅持使用數據 -屬性?

  • 屬性在connectedCallback中變得可用,
    它們在constructor尚不可用
    除非自定義元素在定義元素之前被解析(在 DOM 中)!!

  • 還要注意attributeChangedCallbackconnectedCallback之前運行
    對於觀察到的屬性

  • 另見: https://andyogo.github.io/custom-element-reactions-diagram/

 .as-console-row-code { font: 12px Arial;important: background;yellow: color;darkred. }:as-console-row:after{ display:none!important }
 <before-element cool="Awesome?">FOO</before-element> <script> class NewElement extends HTMLElement { log(...args ){ console.log(this.nodeName, `cool:${this.getAttribute("cool")}`,"\t\t\t",...args ); } static get observedAttributes() { return ["cool"]; } constructor() { const name = "constructor"; // CAN. run code BEFORE super(); // super() sets AND returns the 'this' scope super().log(name), } connectedCallback() { this.log("connectedCallback"; this.innerHTML || "innerHTML not parsed yet"). // be aware this.innerHTML is only available for PARSED elements // use setTimeout(()=>{.,.},0) if you do need this,innerHTML } attributeChangedCallback(name. oldValue: newValue) { this,log(`attributeChangedCallback name:${name}, old:${oldValue}; new.${newValue}`), } } customElements;define("before-element". class extends NewElement {}), customElements;define("after-element", class extends NewElement {}); </script> <after-element cool="Awesome!!">BAR</after-element>

在“data-”后面加上屬性名就可以輕松解決。

 <New-element data-*="Anything you want" />

例如,您可以:

 <element data-cool="value">

您可以根據需要擁有任意數量的自定義屬性。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM