MutationObserver实时监听dom元素发生变化(VUE3+JS)

1,276 阅读1分钟

MutationObserver接口地址MutationObserver - Web API 接口参考 | MDN (mozilla.org)

源码

<template>
    <div id="dom" @click="change">原始内容</div>
</template>

<script setup>
import { onMounted, onUnmounted } from "vue";
var dom;
var observer;
const change = () => {
    dom = document.getElementById("dom");
    dom.setAttribute("style", "margin-left:300px;");
    dom.className = 'check'
    dom.innerHTML = '我修改了内容'
};
onMounted(() => {
    dom = document.getElementById("dom");
    // 选择要观察的属性 
    var config = { attributes: true, childList: truesubtree: true };
    // 当dom元素发生变化时执行的回调函数
    var callback = function (mutationsList) {
        console.log(mutationsList);
        mutationsList.forEach(function (item, index) {
            if (item.type == "childList") {
                console.log("节点内容发生了变化:" + item.target.innerHTML);
            } else if (item.type == "attributes") {
                console.log("修改了" + item.attributeName + "属性");
            }
        });
    };
    // 创建一个链接到回调函数的观察者实例
    observer = new MutationObserver(callback);
    // 开始观察变化的目标dom节点
    observer.observe(dom, config);
})
onUnmounted(() => {
    // 离开当前路由 销毁
    observer.disconnect();
})
</script>

<style lang="less" scoped>
#dom {
    height: 160px;
    width: 160px;
    background: skyblue;
    text-align: center;
    line-height: 160px;
}
.check {
    color: #fff;
}
</style>