vue3监听需要读取dom的ref实例。

<div class="right" ref="myButton">我要变化宽度</div>

<script setup lang="ts">
    const myButton = ref(null);
    let observer: ResizeObserver | null = null;

    onMounted(() => {
        observer = new ResizeObserver(handleResize);
        observer.observe(myButton.value);
    });
    const handleResize = (entries: any) => {
        for (const entry of entries) {
          const { width, height } = entry.contentRect;
          console.log(`宽度:${width}px,高度:${height}px`);
          // 这里可以执行针对宽高变化的操作
        }
     };
    onUnmounted(() => {
        // 在组件销毁前取消观察
        if (observer) {
            observer.disconnect();
        }
     });

</script>

如果要在最后一次进行操作的话可以加一个定时器。先清除上一次的定时器,最后再执行一次定时器,这样就会在最后的宽高执行了。适用与需要监听的dom元素在改变宽高时有过度效果的情况下。

const myButton = ref(null);
let observer: ResizeObserver | null = null;
let resizeTimer: any = null;

onMounted(() => {
    initG6();
    observer = new ResizeObserver(handleResize);
    observer.observe(myButton.value);
});
const handleResize = (entries: any) => {
    clearTimeout(resizeTimer);
    resizeTimer = setTimeout(() => {
        for (const entry of entries) {
            const { width, height } = entry.contentRect;
            console.log(`宽度:${width}px,高度:${height}px`);
            graph.changeSize(width, height);
            // 这里可以执行针对宽高变化的操作
        }
    }, 200);
};
onUnmounted(() => {
    // 在组件销毁前取消观察
    if (observer) {
        observer.disconnect();
    }
});

GitHub 加速计划 / vu / vue
207.52 K
33.66 K
下载
vuejs/vue: 是一个用于构建用户界面的 JavaScript 框架,具有简洁的语法和丰富的组件库,可以用于开发单页面应用程序和多页面应用程序。
最近提交(Master分支:1 个月前 )
73486cb5 * chore: fix link broken Signed-off-by: snoppy <michaleli@foxmail.com> * Update packages/template-compiler/README.md [skip ci] --------- Signed-off-by: snoppy <michaleli@foxmail.com> Co-authored-by: Eduardo San Martin Morote <posva@users.noreply.github.com> 3 个月前
e428d891 Updated Browser Compatibility reference. The previous currently returns HTTP 404. 3 个月前
Logo

旨在为数千万中国开发者提供一个无缝且高效的云端环境,以支持学习、使用和贡献开源项目。

更多推荐