当前位置:   article > 正文

关于ResizeObserver用于监听元素尺寸变化_vue3 resizeobserver

vue3 resizeobserver

以下代码案例皆属于vue3

xxx/index.ts文件

/**
 * @description: 防抖
 * @return {*}
 */
export const useDebounce = (() => {
  let timer: number;
  return (callback: (...args: any[]) => any, wait: number = 200) => {
    clearTimeout(timer);
    timer = setTimeout(callback, wait);
  }
})()
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11

xxx/directive.ts文件

import { App, computed, Directive } from 'vue';
import { useDebounce } from './index';

// 监听元素变化指令
type CallBackType = {
  width: number;
  height: number;
}
const weakMap = new WeakMap<Element, (arg: CallBackType) => any>();
const useElemResize: Directive<HTMLElement, (arg: CallBackType) => any> = {
  mounted(el, binding){ // 挂载后
    weakMap.set(el, binding.value);
    resizeObserver.observe(el);
  },
  beforeUnmount(el){ // 卸载前
    weakMap.delete(el);
    resizeObserver.unobserve(el);
  }
}
const resizeObserver = new ResizeObserver(entries => { // 元素监视
  for (const entry of entries) {
    const callback = weakMap.get(entry.target);
    if(callback && typeof callback === 'function'){
      useDebounce(() => {
        callback({
          width: entry.borderBoxSize[0].inlineSize,
          height: entry.borderBoxSize[0].blockSize
        })
      })
    }
  }
});
// 监听元素变化指令

export default () => {
  return {
    install(app: App<Element>){
      app.directive('resize', useElemResize);
    }
  }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41

main.ts文件

import { createApp } from 'vue';
import App from './App.vue';
import directive from '@utils/directive';

const app = createApp(App);
app.use(directive());
app.mount('#app');
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7

使用

<template>
	<div v-resize="divResize"></div>
</template>

<script lang="ts" setup>
const divResize = (params: { width: number; height: number; }) => {
	console.log(params);
}
</script>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/你好赵伟/article/detail/223159
推荐阅读
相关标签
  

闽ICP备14008679号