繁体   English   中英

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

[英]Is it possible to inject custom attributes / properties into native web components?

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

这是我的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>

是和否。

没有任何内置的模板。 但这并不意味着你不能这样做。

 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为您处理它。 你能提供更多关于你想用这个函数做什么的细节吗

这里有两个有用的问题/答案: * 标签中的自定义 Web 组件事件回调函数* 我可以将函数作为属性传递给 Web 组件吗?

更新

当设置了多个属性或属性时,有人问到如何避免比需要更频繁地渲染。 这通常被称为“去抖动”。

这是一种选择:

let renderTimeout = null;
function render(el) {
  if (renderTimeout) {
    clearTimeout(renderTimeout);
  }

  renderTimeout = setTimeout(() => {
    el.shadowRoot.innerHTML = `<div>${el._test}</div>`;
  }, 0);
}

这将设置一个0时间超时,这意味着它会尽快发生,通常是在当前代码完成运行后。 然后渲染操作将发生。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM