0

我和我的朋友正在尝试制作一个允许用户制作元素并自定义它们的 javascript 框架。以及以某种方式管理它们。

我们希望我们能以某种方式制作这样的自定义元素

class Header extends HTMLElement {

  constructor() {
    super();

  }

  connectedCallback(){

    this.title = this.getAttribute("title")
    console.log(this.getAttribute("title"))

    if(this.hasAttribute("drawer-button")){

    }

    this.innerHTML = 
      `
      <div class="--e-header-1">
        <e-button></e-button>
        <div class="header-title">
          <h1>${this.title}</h1>
        </div>
      </div>
      `
  }

}

customElements.define('e-header', Header);

你可以像这样在 HTML 中使用它很酷,<e-header></e-header>但我们希望我们可以做这样的事情


var el = new Header(//put in options maybe);
document.append(el)

我们不断收到此错误Uncaught TypeError: Illegal constructor

我们将如何去做这样的事情,我们是否走在正确的轨道上

4

1 回答 1

1

你想做这样的事情吗?

我已将选项传递title给班级并将其设置在班级中。

class Header extends HTMLElement {

  constructor(options) {
    super();
    this.title = options.title;
  }

  connectedCallback() {
    this.title = this.getAttribute("title")
    console.log(this.getAttribute("title"))

    if (this.hasAttribute("drawer-button")) {

    }

    this.innerHTML =
      `
      <div class="--e-header-1">
        <e-button></e-button>
        <div class="header-title">
          <h1>${this.title}</h1>
        </div>
      </div>
      `
  }

}

customElements.define('e-header', Header);

var el = new Header({
  'title': 'headerTitle'
});
document.body.append(el)

于 2020-05-01T09:40:48.470 回答