【问题标题】:Creating a page building framework in javascript utilizing customElements使用 customElements 在 javascript 中创建页面构建框架
【发布时间】:2020-08-15 18:52:31
【问题描述】:

我和我的朋友正在尝试制作一个允许用户制作元素并自定义它们的 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);

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


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

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

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

【问题讨论】:

  • 错误来自document.append(el),应该是document.body.append(el)

标签: javascript custom-element html-templates


【解决方案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)

【讨论】:

  • 这正是我们想要的,非常感谢。
  • 更通用,做Object.assign(this,options)而不是硬编码this.title=options.title 并且你可以设置默认值:constructor({title='No Title'})
猜你喜欢
  • 2015-08-25
  • 1970-01-01
  • 1970-01-01
  • 2015-11-06
  • 2014-08-13
  • 2012-01-25
  • 1970-01-01
  • 2011-04-12
  • 1970-01-01
相关资源
最近更新 更多