1、安装resize-observer-polyfill
npm install resize-observer-polyfill --save-dev
2、在utils文件夹下的index.ts引入使用
import ResizeObserver from 'resize-observer-polyfill'
/**
* @description 监听dom的宽高变化
* @param {ElementDom} targetNode 需监听的dom
* @param {Function} throttleTime 监听的频率
* @param {Number} callback 回调函数
* @returns resizeObserver
*/
export const listenDomChange = function (targetNode: Element, callback: any, throttleTime = 300) {
const _callback = throttle(callback, throttleTime)
const observer = new ResizeObserver(_callback)
observer.observe(targetNode)
return observer
}
3、组件内使用
<template>
<div class="mapContainer container" ref="mapContainer">高度变化</div>
</template>
<script lang="ts" setup>
import { listenDomChange } from '@/utils'
const mapContainer = shallowRef<HTMLDivElement | null>(null)
onMounted(function () {
listenMapChange()
})
/**
* @description 监听容器宽高的变化
*/
const listenMapChange = function () {
const targetNode = mapContainer.value
// 观察器的配置
listenDomChange(targetNode!, () => {
reSizeMap()
})
}
/**
* @description 更新地图的宽高
*/
const reSizeMap = () => {
console.log('高度变化', mapContainer.value?.clientHeight)
}
</script>
<style lang="scss" scoped>
.mapContainer {
width: 100%;
height: calc(100vh - 80px);
position: relative;
z-index: 10;
}
</style>