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文档

相关推荐
空中海19 分钟前
04 React Native工程化、质量、发布与生态选型
javascript·react native·react.js
AI砖家24 分钟前
Claude Code Superpowers 安装使用指南:让 AI 编程从“业余”走向“工程化”
前端·人工智能·python·ai编程·代码规范
李白的天不白36 分钟前
webpack 与axios 版本冲突问题
前端·webpack·node.js
承渊政道40 分钟前
【动态规划算法】(完全背包问题从状态定义到空间优化)
数据结构·c++·学习·算法·leetcode·动态规划·哈希算法
玩转单片机与嵌入式43 分钟前
学习嵌入式AI(TInyML),只需掌握这点python基础即可!
人工智能·python·学习
ErizJ1 小时前
Linux|学习笔记
linux·笔记·学习
杨超凡1 小时前
豆包收费了?我特么自己用“意念”搓了一个!
javascript
大数据三康1 小时前
Java字符统计:从输入到输出的完整解析
java·学习·循环结构
Java后端的Ai之路1 小时前
模型调好了怎么给老板看?用这玩意儿5分钟出Demo,连前端都不用学:Gradio 6全栈实战指南
前端·机器学习·gradio