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

相关推荐
四谎真好看17 分钟前
Java 黑马程序员学习笔记(进阶篇31)
java·笔记·学习·学习笔记
xhxxx21 分钟前
AI打字机的秘密:一个 buffer 如何让机器学会“慢慢说话”
前端·vue.js·openai
韩曙亮26 分钟前
【Web APIs】BOM 浏览器对象模型 ⑥ ( location 对象 | location 常用属性和方法 | URL 简介 )
前端·javascript·dom·url·bom·location·浏览器对象模型
用户214118326360226 分钟前
CC-Switch配置切换神器:5秒搞定多设备同步,坚果云让配置永不丢失
前端
勤奋的懒洋洋35036 分钟前
前端实现多个图片打包下载
前端
懵萌长颈鹿42 分钟前
Tkinter 学习文档
学习
YJlio1 小时前
Active Directory 工具学习笔记(10.1):AdExplorer 实战(一)— 连接到域与界面总览
笔记·学习·安全
豐儀麟阁贵1 小时前
9.5格式化字符串
java·开发语言·前端·面试
春生野草1 小时前
Ruoyi前端基于vue的脚手架的目录解析
前端·javascript·vue.js
崇山峻岭之间1 小时前
C++ Prime Plus 学习笔记025
c++·笔记·学习