创建Javascript组件的最佳方法是什么?

问题描述

我正在研究如何在Javascript中创建组件。通过扩展HTMLElement创建组件是一个好主意吗?或还有另一种方式。 如果您能给我建议,那是最好的方法

我正在练习在网上找到的这个示例,这是一个方法吗?

<my-component id="a">Hello</my-component>
<my-component id="b">Hello</my-component>

<script>
 class MyComponent extends HTMLElement {
   get id () {
     console.log ('get id',super.id);
     return super.id;
   }

   set id (value) {
     console.log ('get id',value);
     super.id = value;
   }

   get innerHTML () {
     console.log ('get innerHTML',super.innerHTML);
     return super.innerHTML;
   }

   set innerHTML (value) {
     console.log ('set innerHTML',value);
     super.innerHTML = value;
   }
 }

 customElements.define ('my-component',MyComponent);

 const el1 = document.querySelector ('#a');
 el1.id    = 'c';

 const el2     = document.querySelector ('#b');
 el2.innerHTML = '<h2>Hello</h2>';

</script>

解决方法

这取决于您要查找的内容。如果您要构建一个更复杂的Web应用程序,我建议您使用诸如React,Angular或Vue之类的前端框架,因为它们使编写复杂的前端变得如此优雅。

但是,如果您想更多地了解Web组件和构建前端的不同方法,我鼓励您尝试使用一堆不同的工具和框架来构建简单的项目,以发现自己最喜欢的工具并从中受益。那里。我提到的框架之一可能是一个很好的起点。