是否可以将自定义属性/属性注入本机Web组件?

时间:2019-04-26 15:10:42

标签: javascript html native-web-component

我正在学习Web组件(本机和框架)。是否可以像在Vue.js中那样将属性注入到本机组件中?

这是my-component.js:

const templateComponent = document.createElement('template');
templateComponent.innerHTML = `<div>{{ test }}</div>`;

class MyComponent extends HTMLElement {

    connectedCallback() {
        this._container = this.querySelector("DIV");
    }

}

window.customElements.define("my-component", MyComponent);

这是index.html:

<!doctype html>
<html lang="en">
<head>
    <title>Document</title>
</head>
<body>

<my-component test="Does this work?"></my-component>


<script src="my-component.js"></script>

</body>
</html>

1 个答案:

答案 0 :(得分:1)

是,不是。

没有内置模板。但这并不意味着你做不到。

function render(el) {
  el.shadowRoot.innerHTML = `<div>${el._test}</div>`;
}

class MyComponent extends HTMLElement {
  static get observedAttributes() {
    return ['test'];
  }

  constructor() {
    super();
    this.attachShadow({mode: 'open'});
  }

  attributeChangedCallback(attrName, oldVal, newVal) {
    if (oldVal !== newVal) {
      this[`_${attrName}`] = newVal;
      render(this);
    }
  }
}

window.customElements.define("my-component", MyComponent);
<my-component test="Does this work?"></my-component>
<my-component test="Yes it does"></my-component>

您使用observedAttributes来指示要监视更改的属性。然后,您使用attributeChangedCallback作为其中之一发生更改时的处理程序。

然后由您决定将属性值添加到DOM中。如果DOM很简单,您可以像我一样做,每次都重新生成它即可。

更复杂的事情将需要更复杂的算法。

有些人会告诉您使用LITHtml。我觉得这很烦人。我的大多数组件很小,不需要复杂性。

扩展

是的,您可以将回调函数作为字符串传递。换句话说,您将回调函数的名称作为字符串传递,然后在组件中调用eval但是,我不建议这样做。这样做有很多限制,可以用于邪恶和邪恶目的。 :)

相反:

  • 在组件上提供可以设置为回调函数的属性。
  • 在要使用回调函数调用的组件上提供一个函数
  • 从组件中调度事件,并让addEventListener为您处理事件。您能否提供有关该功能的更多详细信息

以下是两个有用的问题/解答: * custom web component event call back function in tag * can i pass function as attribute to web component?

相关问题