利用customElements在javascript中创建一个页面构建框架。

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

我和我的朋友正在尝试做一个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

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

javascript custom-element html-templates
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)
© www.soinside.com 2019 - 2024. All rights reserved.