MutationObserver用法总结(我知道你们要在vue中想用MutationObserver监听一个特定样式的变化)

如果你想多看看的话,点击这个链接去研究MutationObserver使用方法及配置参考

一般来说拿来用就可以满足需求了

我们有时候会遇到这样一些情况,例如我想要给一个按钮动态的绑定一个样式,这个样式的绑定依赖于我们定义的一个变量,但是该变量也是动态的,变量的值依赖于另外一个内部组件样式的变化

这是我在vue中使用技巧============================》

script如下:

export default {
  name: "HelloWorld",
  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"]
      });
    },
  },
};

模板如下:

<template>
  <div :class="{'mycolor':isActive}" class="hello">
    <el-button
      type="primary"
      class="el-button"
      @click.stop="openDialog"
      >点击</el-button
    >
    <el-dialog
      ref="dialog"
      title="我是dialog"
      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>

用起来还是很方便的,一看就会了,欢迎大家一起交流哈~~~~~

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值