Web Components系列(七) ——自定义组件的生命周期

简介: 何谓”生命周期“?顾名思义,生命周期就是指一个物体从产生前到消亡后的整个过程,当然,不同物体的生命周期具体阶段划分可能不太一样。

19.png


前言


何谓”生命周期“?顾名思义,生命周期就是指一个物体从产生前到消亡后的整个过程,当然,不同物体的生命周期具体阶段划分可能不太一样。


我们在使用前端组件框架的时候,都知道每个组件都有各自的生命周期,明确了组件生命周期后,开发者就可以在组件的不同生命周期执行不同的代码逻辑,从而达到管理组件的作用。


为了使 Custom Elements 在使用上更加灵活,它也有”生命周期“回调函数,可以让开发者定义好在组件不同生命时期可以被执行的方法。


Custom Elements 生命周期划分


在 Custom Elements 的构造函数中,可以指定多个不同的回调函数,它们将会在元素的不同生命时期被调用:


  • connectedCallback:当 Custom Elements首次被插入文档DOM时,被调用。
  • disconnectedCallback:当 Custom Elements 从文档DOM中删除时,被调用。
  • adoptedCallback:当 Custom Elements 被移动到新的文档时,被调用。
  • attributeChangedCallback: 当 Custom Elements 增加、删除、修改自身属性时,被调用。


注意:自定义元素的生命周期回调函数是被使用在它的构造函数中的。


生命周期回调函数的使用


首先看一下效果:


网络异常,图片无法展示
|


这里需要注意的是:adoptedCallback 回调只有在将自定义元素移动到新文档(一般是 iframe)中时才会被触发


代码如下:


<!--index.html-->
<head>
    <style>
        body {
            padding: 50px;
        }
        custom-square {
            margin: 15px;
        }
        iframe {
            width: 100%;
            height: 250px;
            overflow: hidden;
        }
    </style>
</head>
<body>
    <h1>Custom Elements 生命周期</h1>
    <div>
        <button class="add">追加 Square 到 DOM</button>
        <button class="update">改变 Square 的属性</button>
        <button class="remove">移除 Square 元素</button>
        <button class="move">移动 Square 到 Iframe</button>
    </div>
    <iframe src="./other.html"></iframe>
    <script src="./square.js"></script>
    <script src="./index.js"></script>
</body>
<!--other.html-->
<body>
    <h1>这是 other.html</h1>
</body>


// square.js
function updateStyle(elem) {
    const shadow = elem.shadowRoot;
    shadow.querySelector("style").textContent = `
      div {
        width: ${elem.getAttribute("l")}px;
        height: ${elem.getAttribute("l")}px;
        background-color: ${elem.getAttribute("c")};
      }
    `;
}
class Square extends HTMLElement {
    static get observedAttributes() {
        return ["c", "l"];
    }
    constructor() {
        super();
        const shadow = this.attachShadow({ mode: "open" });
        const div = document.createElement("div");
        const style = document.createElement("style");
        shadow.appendChild(style);
        shadow.appendChild(div);
    }
    connectedCallback() {
        console.log("custom-square 被挂载到页面");
        updateStyle(this);
    }
    disconnectedCallback() {
        console.log("custom-square 从页面被移除");
    }
    adoptedCallback() {
        console.log("custom-square 被移动到新页面");
    }
    attributeChangedCallback(name, oldValue, newValue) {
        console.log("custom-square 属性值被改变");
        updateStyle(this);
    }
}
customElements.define("custom-square", Square);


// index.js
const add = document.querySelector(".add");
const update = document.querySelector(".update");
const remove = document.querySelector(".remove");
const move = document.querySelector(".move");
let square;
update.disabled = true;
remove.disabled = true;
function random(min, max) {
    return Math.floor(Math.random() * (max - min + 1) + min);
}
add.onclick = function () {
    // Create a custom square element
    square = document.createElement("custom-square");
    square.setAttribute("l", "100");
    square.setAttribute("c", "red");
    document.body.appendChild(square);
    update.disabled = false;
    remove.disabled = false;
    add.disabled = true;
};
update.onclick = function () {
    // Randomly update square's attributes
    square.setAttribute("l", random(50, 200));
    square.setAttribute("c", `rgb(${random(0, 255)}, ${random(0, 255)}, ${random(0, 255)})`);
};
remove.onclick = function () {
    // Remove the square
    document.body.removeChild(square);
    update.disabled = true;
    remove.disabled = true;
    add.disabled = false;
};
update.onclick = function () {
    // Randomly update square's attributes
    square.setAttribute("l", random(50, 200));
    square.setAttribute("c", `rgb(${random(0, 255)}, ${random(0, 255)}, ${random(0, 255)})`);
};
move.onclick = function () {
    window.frames[0].document.body.appendChild(square);
}


结束语


以上就是 Custom Elements 生命周期回调函数的简单使用示例,希望能对你有所帮助!


Custom Elements 的回调函数中,adoptedCallback 的使用场景较少,这个需要注意。


~ 本文完,感谢阅读!


学习有趣的知识,结识有趣的朋友,塑造有趣的灵魂!




相关文章
|
4月前
|
XML 编解码 前端开发
【web组件库系列】封装自己的字体图标库
【web组件库系列】封装自己的字体图标库
59 0
|
5月前
|
Java 数据库连接 容器
8:Servlet生命周期-Java Web
8:Servlet生命周期-Java Web
28 0
|
2月前
|
消息中间件 druid Java
web后端-SpringCloud-Bus消息总线组件
web后端-SpringCloud-Bus消息总线组件
|
4月前
|
Java 应用服务中间件 容器
SpringBoot之Web原生组件注入
SpringBoot之Web原生组件注入
|
3月前
|
IDE API 开发工具
 鸿蒙(HarmonyOS)项目方舟框架(ArkUI)之Web组件
 鸿蒙(HarmonyOS)项目方舟框架(ArkUI)之Web组件
47 2
|
5天前
|
SQL 分布式计算 资源调度
常用大数据组件的Web端口号总结
这是关于常用大数据组件Web端口号的总结。通过虚拟机名+端口号可访问各组件服务:Hadoop HDFS的9870,YARN的ResourceManager的8088和JobHistoryServer的19888,Zeppelin的8000,HBase的10610,Hive的10002。ZooKeeper的端口包括客户端连接的2181,服务器间通信的2888以及选举通信的3888。
18 2
常用大数据组件的Web端口号总结
|
11天前
|
移动开发 JavaScript 前端开发
【专栏:HTML进阶篇】HTML模板与Web组件:可复用的网页元素
【4月更文挑战第30天】HTML模板和Web组件提升网页开发效率和可维护性。HTML模板,如&lt;template&gt;元素和服务器端模板引擎,用于创建可复用的HTML结构。Web组件是自定义的HTML元素,结合影子DOM和模板,实现封装的可重用组件。两者助力构建高效、现代的网页和网站。
|
26天前
|
前端开发 JavaScript vr&ar
前端新技术探索:WebAssembly、Web Components与WebVR/AR
【4月更文挑战第12天】WebAssembly、Web Components和WebVR/AR正重塑Web应用的未来。WebAssembly允许C/C++等语言在Web上高效运行,提供接近原生的性能,如游戏引擎。Web Components通过Custom Elements和Shadow DOM实现可复用的自定义UI组件,提升模块化开发。WebVR/AR(现WebXR)则让VR/AR体验无需额外应用,直接在浏览器中实现。掌握这些技术对前端开发者至关重要。
16 3
|
3月前
|
JavaScript 前端开发 API
「深入探究Web页面生命周期:DOMContentLoaded、load、beforeunload和unload事件」
在 Web 开发中,了解页面生命周期是非常重要的。页面生命周期定义了页面从加载到卸载的整个过程,包括各种事件和阶段。在本文中,我们将详细介绍四个关键事件:DOMContentLoaded、load、beforeunload 和 unload。我们将探讨这些事件的属性、API、应用场景,并提供一些代码示例和参考资料。
|
4月前
|
前端开发
【web组件库系列】纯CSS实现典型网页数据分页器
【web组件库系列】纯CSS实现典型网页数据分页器
48 0