MutationObserver 之前写过一篇详解,具体可参考:https://blog.csdn.net/qq_36020334/article/details/156300319?spm=1001.2014.3001.5502
在前端基于Vue的开发中,Vue2用watch来监听数据的变化,通过deep属性的配置项来监听对象内部的变化。 在 Vue3 中使用 proxy 替代了defineProperty 来监听整个对象,便利程度大大提高。
但有时候会遇到这样一些特殊情况,例如:想要给一个按钮动态的绑定一个样式,这个样式的绑定依赖于定义的一个变量,但是该变量也是动态的,变量的值依赖于另外一个内部组件样式的变化。 这就用到了 MutationObserver 去监听一个特定样式的变化,进而去实现业务的需求
代码实现:
<template> <div :class="{'mycolor':isActive}" class="content"> <el-button type="primary" class="el-button" @click.stop="openDialog" >打开弹窗</el-button > <el-dialog ref="dialog" title="我是弹窗啊" width="300px" :visible="false" :before-close="dialogBeforeClose" > <div></div> <div slot="footer"> <el-button @click="dialogBeforeClose">取 消</el-button> <el-button type="primary" @click="dialogBeforeClose">确 定</el-button> </div> </el-dialog> </div> </template> <script> export default { name: "testContent", data() { return { isActive: false, }; }, mounted() { this.$nextTick(() => { this.watchDialogStyle(this.$refs.dialog.$el); }); }, methods: { openDialog() { this.$refs.dialog.$el.style.display = "block"; }, dialogBeforeClose() { this.$refs.dialog.$el.style.display = "none"; }, watchDialogStyle(dialog) { const observer = new MutationObserver( (mutations) => { mutations.forEach((mutation) => { if(dialog.style.display === 'none'){ this.isActive = true; } else{ this.isActive = false; } }); }); observer.observe(dialog, { attributeFilter: ["style"] }); }, }, }; </script>