赞
踩
以下代码案例皆属于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);
}
})()
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); } } }
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');
使用
<template>
<div v-resize="divResize"></div>
</template>
<script lang="ts" setup>
const divResize = (params: { width: number; height: number; }) => {
console.log(params);
}
</script>
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。