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

相关推荐
excel16 小时前
nuxt 3 升级 nuxt 4 报错之 hasInjectionContext
前端
小磊哥er16 小时前
深入解构Claude Code - 第 7 篇 · 连接外面的世界
javascript·ai编程
何以解忧,唯有..16 小时前
LangChain 工具调用(Tool Calling)实战指南
java·前端·langchain
小磊哥er16 小时前
深入解构Claude Code - 第 6 篇 · 终端里的图形界面
javascript·ai编程
海兰16 小时前
【应用】基于 Next.js 16 + Python mplfinance的金融K线图与技术指标可视化平台(一)
javascript·python·金融
大衛說16 小时前
《Python 从入门到精通》系列总览与学习路线
开发语言·python·学习
软件聚导航17 小时前
「聚小软 AI 助手」技术升级:从数据库检索到 RAG 知识库问答
前端·数据库·mysql·微信小程序·小程序·ai编程·rag
吃好睡好便好17 小时前
查找函数的使用
学习·算法·matlab·生活·查找函数
学运维的Kysan17 小时前
暑假运维学习打卡第二十九天8.29
学习
恋猫de小郭17 小时前
看懂大模型架构术语,帮助你理解目前常见的大模型开源架构
前端·人工智能·ai编程