前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Web Components系列(七) ——自定义组件的生命周期

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

原创
作者头像
编程三昧
发布2022-02-13 22:46:28
8500
发布2022-02-13 22:46:28
举报
文章被收录于专栏:编程三昧编程三昧

前言

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

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

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

Custom Elements 生命周期划分

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

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

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

生命周期回调函数的使用

首先看一下效果:

2022-02-12 23.43.06
2022-02-12 23.43.06

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

代码如下:

代码语言:html
复制
<!--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>

代码语言:javascript
复制
// 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);

代码语言:javascript
复制
// 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 的使用场景较少,这个需要注意。

~ 本文完,感谢阅读!

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

大家好,我是作者 隐逸王,希望大家多多指教!

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 前言
  • Custom Elements 生命周期划分
  • 生命周期回调函数的使用
  • 结束语
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档