在 Web 组件中重写 setAttribute

问题描述 投票:0回答:1

我正在构建一个 Web 组件包装器。在此包装器中,我想在构建组件后动态定义观察到的属性。

根据我的理解,没有简单的方法可以做到这一点,因为您需要在类声明期间定义

observedAttributes

我发现您甚至不需要使用

observedAttributes
attributeChangedCallback()
:您只需覆盖
setAttribute
即可。

class MyClass extends HTMLElement {
      constructor() {
        super();
        // attach shadow etc
      }
      connectedCallback() {
        // handle attribute initialization, render
      }
      setAttribute(name, value) {
        super.setAttribute(name, value);
        // handle attribute change, re-render
      }
}

window.customElements.define("my-element", MyClass);

这听起来太容易了,不太真实。这样的做法有什么问题吗?

web-component custom-element
1个回答
0
投票
回复:评论

不,

setAttribute
不会触发
attributechangedCallback

只有

observedAttribute
才会触发
attributeChangedCallback

单击下面代码中的

<button> B
仅运行(重载)
setAttribute

单击

<button> A
会触发
attributeChangedCallback
之前 他(超载)
setAttribute

<base-component a="foo" id=TEST>Hello Web Component</base-component>
<script>
const BR = () => document.createElement("BR");
const LOG = (...args) => document.body.append(BR(),...args.join(" "));
customElements.define("base-component", class extends HTMLElement {
  static get observedAttributes() {
    return ["a"];
  }
  setAttribute(name, value) {
    super.setAttribute(name, value);
    LOG("setAttribute", name, value);
  }
  attributeChangedCallback(name, oldValue, newValue) {
    LOG("attributeChangedCallback", name, oldValue,newValue);
  }
});
</script>
<button onclick='TEST.setAttribute("a", "status 1");'>A</button>
<button onclick='TEST.setAttribute("b", "status 2");'>B</button>

© www.soinside.com 2019 - 2024. All rights reserved.