什么是 Web Components ?
    Web Components 是一个浏览器原生支持的组件化方案,允许你创建新的自定义、可封装、可重用的HTML 标记。不用加载任何外部模块,直接就可以在浏览器中跑。
    Web Components 存在的目的就是希望提供给开发者,能够自定义可重用的、可被浏览器正常解析的标签,让逻辑、样式、标签都封装在一个组件内部,最终用自定义的标签渲染视图。

    Vue 的模版系统本身是参考 Web Components 的规范进行了上层的设计,因为 Web Components 拥有:自定义标签、自定义属性、自定义组件的特点。

    例如我们想要创建一个自定义的组件:

    1. <my-info
    2. avatar="https://cdn.pixabay.com/photo/2023/02/13/05/58/doodle-7786568__340.png"
    3. name="xiechen"
    4. age="22"
    5. occupation="student">
    6. The infomation of xiechen.
    7. </my-info>
    1. // 需要继承 HTMLElement 类
    2. window.customElements.define("my-info", class extends HTMLElement {
    3. constructor() {
    4. super();
    5. // 这里的 this 指向的就是我们的 my-info 标签本身
    6. this.title = this.textContent;
    7. this.avatar = this.getAttribute("avatar");
    8. this.myName = this.getAttribute("name");
    9. this.age = this.getAttribute("age");
    10. this.occupation = this.getAttribute("occupation");
    11. this.init();
    12. }
    13. init() {
    14. var shdowDOM = this.attachShadow({
    15. mode: "open"
    16. });
    17. shdowDOM.appendChild(this.createDOM());
    18. }
    19. createDOM() {
    20. // 创建需要的 DOM
    21. var oContainer = this.createContainer();
    22. oContainer.appendChild(this.createTitle());
    23. oContainer.appendChild(this.createAvatar());
    24. oContainer.appendChild(this.createName());
    25. oContainer.appendChild(this.createAge());
    26. oContainer.appendChild(this.createOccupation());
    27. return oContainer;
    28. }
    29. createContainer() {
    30. var oContainer = document.createElement("div");
    31. oContainer.className = "my-info-container";
    32. return oContainer;
    33. }
    34. createTitle() {
    35. var oTitle = document.createElement("h1");
    36. oTitle.className = "my-info-title";
    37. oTitle.textContent = this.title;
    38. return oTitle;
    39. }
    40. createAvatar() {
    41. var oImage = document.createElement("img");
    42. oImage.className = "my-info-avatar";
    43. oImage.style.width = "200px";
    44. oImage.src = this.avatar;
    45. return oImage;
    46. }
    47. createName() {
    48. var oName = document.createElement("p");
    49. oName.className = "my-info-name";
    50. oName.textContent = this.myName;
    51. return oName;
    52. }
    53. createAge() {
    54. var oAge = document.createElement("p");
    55. oAge.className = "my-info-age";
    56. oAge.textContent = this.age;
    57. return oAge;
    58. }
    59. createOccupation() {
    60. var oOccupation = document.createElement("p");
    61. oOccupation.className = "my-info-occupation";
    62. oOccupation.textContent = this.occupation;
    63. return oOccupation;
    64. }
    65. }
    66. );

    image.png