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

相关推荐
夜郎king1 小时前
湖南高考天气查询:基于 HTML5 与百度天气 API 实现页面展示
前端·html5·百度天气实践·天气信息可视化
云水一下8 小时前
TypeScript 从零基础到精通(五):高级类型与泛型
前端·javascript·typescript
counterxing8 小时前
vibe coding 之后,我更不想打字了
前端·agent·ai编程
努力学习_小白8 小时前
ResNeXt-50——学习记录
pytorch·深度学习·学习
云水一下8 小时前
TypeScript 从零基础到精通(六):类型声明与模块化
javascript·typescript
copyer_xyf8 小时前
Python 模块与包的导入导出
前端·后端·python
研☆香9 小时前
es6新特性功能介绍(四)
前端·ecmascript·es6
微扬嘴角9 小时前
React篇1--JSX语法规则、组件、组件实例的3大特性
前端·react.js·前端框架
copyer_xyf9 小时前
Python venv 虚拟环境
前端·后端·python
无聊的老谢9 小时前
Vue 3 + TypeScript 构建大型电信运维平台的前端架构设计
前端·vue.js·typescript