webcomponents学习

一、新建index.html文件

html 复制代码
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <div>我是你大哥</div>
    <!-- 传递参数,可以看出来和vue的使用方法差不多 -->
    <wu-jie  url="baidu.com" age="18"></wu-jie>
    <template id="wujie">
      <style>
        .box {
          width: 100px;
          height: 100px;
          background-color: red;
        }
      </style>
      <div class="box">你好呀</div>
    </template>
  </body>
  <script src="./index.js"></script>
</html>

二、新建index.js文件

javascript 复制代码
"use strict";
window.onload = () => {
    class Wujie extends HTMLElement {
        constructor() {
            super();
            const dom = this.attachShadow({ mode: "open" });  //开启样式隔绝
            const template = document.getElementById("wujie");  //获取到index.html中的template
            dom.appendChild(template.content.cloneNode(true));  //这里必须要克隆
            console.log(this.#getAttr("age"));
        }
        #getAttr(attr) {
            return this.getAttribute(attr); //通过getAttribute获取属性值
        }
        // 生命周期卸载
        disconnectedCallback() {
            console.log("类似于vue的destory");
        }
        // 生命周期创建
        connectedCallback() {
            console.log("类似于vue的mouted");
        }
        // 类似于watch
        attributeChangedCallback(name, oldValue, newValue) {
            console.log(name, oldValue, newValue);
        }
    }
    window.customElements.define("wu-jie", Wujie); //全局挂载,相当于vue的组件
};

更多知识看MDN文档

相关推荐
Hello_Embed3 小时前
STM32HAL 快速入门(二十):UART 中断改进 —— 环形缓冲区解决数据丢失
笔记·stm32·单片机·学习·嵌入式软件
咸甜适中3 小时前
rust语言 (1.88) 学习笔记:客户端和服务器端同在一个项目中
笔记·学习·rust
人工智能训练师3 小时前
Ubuntu22.04如何安装新版本的Node.js和npm
linux·运维·前端·人工智能·ubuntu·npm·node.js
Seveny073 小时前
pnpm相对于npm,yarn的优势
前端·npm·node.js
Magnetic_h4 小时前
【iOS】设计模式复习
笔记·学习·ios·设计模式·objective-c·cocoa
yddddddy4 小时前
css的基本知识
前端·css
昔人'4 小时前
css `lh`单位
前端·css
研梦非凡4 小时前
ICCV 2025|从粗到细:用于高效3D高斯溅射的可学习离散小波变换
人工智能·深度学习·学习·3d
前端君5 小时前
实现最大异步并发执行队列
javascript
limengshi1383926 小时前
机器学习面试:请介绍几种常用的学习率衰减方式
人工智能·学习·机器学习