1 // resizeObserver.ts 2 // 监听元素大小变化的指令 3 const map = new WeakMap() 4 const ob = new ResizeObserver((entries) => { 5 for (const entry of entries) { 6 // 获取dom元素的回调 7 const handler = map.get(entry.target) 8 //存在回调函数 9 if (handler) { 10 // 将监听的值给回调函数 11 handler({ 12 width: entry.borderBoxSize[0].inlineSize, 13 height: entry.borderBoxSize[0].blockSize 14 }) 15 } 16 } 17 }) 18 19 export const Resize = { 20 mounted(el: any, binding: any) { 21 //将dom与回调的关系塞入map 22 map.set(el, binding.value) 23 //监听el元素的变化 24 ob.observe(el) 25 }, 26 unmounted(el: any) { 27 //取消监听 28 ob.unobserve(el) 29 } 30 } 31 32 export default Resize
// index.ts import { Resize } from './resizeObserver' // 自定义指令集合 const directives: any = { Resize } export default { install(app: any) { Object.keys(directives).forEach((key) => { app.directive(key, directives[key]) }) } }
// 在mian.ts中注册指令
import { createApp } from 'vue' import directives from '@/utils/directive/index' const app = createApp(App) app.use(ElementPlus, { locale: en }) app.use(directives)
使用
<template> <div id="mapContainer" v-resize="onResize" class="map-container" > </div> </template> <script setup lang="ts"> const onResize = (dom: any) => { // console.log(dom) // dom为元素变化后的宽高 } </script>
标签:el,const,自定义,dom,app,directives,vue3,封装,any From: https://www.cnblogs.com/Hhuizi/p/18001136