vue监听ref绑定元素高度变化时

在Vue中,监听一个元素的高度变化可以通过几种方式实现。如果你使用的是Vue 2,你可以使用MutationObserver来监听DOM的变化。Vue 3引入了Composition API,提供了reactiveref等响应式API,可以更简单地实现这一功能。

以下是几种实现监听元素高度变化的方法:

Vue 2 使用 MutationObserver

export default {
  mounted() {
    this.observeHeight();
  },
  methods: {
    observeHeight() {
      const element = this.$refs.myElement;
      const observer = new MutationObserver(mutations => {
        mutations.forEach(mutation => {
          if (mutation.type === 'attributes' && mutation.attributeName === 'style') {
            console.log('Height changed:', element.offsetHeight);
          }
        });
      });

      observer.observe(element, { attributes: true, attributeFilter: ['style'] });

      // 销毁时移除监听
      this.$once('hook:beforeDestroy', () => {
        observer.disconnect();
      });
    }
  }
};

Vue 3 使用 Composition API

在Vue 3中,你可以使用watch来监听一个响应式引用(ref)的变化:

import { ref, watch, onMounted, onBeforeUnmount } from 'vue';

export default {
  setup() {
    const elementRef = ref(null);
    const height = ref(0);

    const updateHeight = () => {
      height.value = elementRef.value.offsetHeight;
    };

    const observer = new ResizeObserver(() => {
      updateHeight();
    });

    onMounted(() => {
      updateHeight();
      observer.observe(elementRef.value);
    });

    onBeforeUnmount(() => {
      observer.disconnect();
    });

    watch(height, (newHeight, oldHeight) => {
      console.log(`Height changed from ${oldHeight}px to ${newHeight}px`);
    });

    return {
      elementRef,
    };
  },
};

在模板中使用elementRef

<template>
  <div ref="elementRef">
    <!-- 内容 -->
  </div>
</template>

使用 ResizeObserver (Vue 2 和 Vue 3)

ResizeObserver是一个现代浏览器提供的API,用于监听元素尺寸的变化。你可以在Vue的任何版本中使用它:

export default {
  mounted() {
    this.observeWithResizeObserver();
  },
  methods: {
    observeWithResizeObserver() {
      const element = this.$refs.myElement;
      const observer = new ResizeObserver(entries => {
        entries.forEach(entry => {
          console.log('Height changed:', entry.contentRect.height);
        });
      });

      observer.observe(element);

      // 销毁时移除监听
      this.$once('hook:beforeDestroy', () => {
        observer.disconnect();
      });
    }
  }
};

在模板中使用ref

<template>
  <div ref="myElement">
    <!-- 内容 -->
  </div>
</template>

使用ResizeObserver是监听元素尺寸变化的推荐方式,因为它是专门为这个目的设计的,并且性能通常优于MutationObserver。然而,ResizeObserver可能不被所有浏览器支持,因此在使用时需要注意兼容性问题。

  • 2
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值