vue3 監(jiān)聽(tīng)頁(yè)面元素變化

引用于https://blog.csdn.net/M__O__M/article/details/129139582

1、安裝resize-observer-polyfill

npm install resize-observer-polyfill --save-dev

2、在utils文件夾下的index.ts引入使用

import ResizeObserver from 'resize-observer-polyfill'
/**
 * @description 監(jiān)聽(tīng)dom的寬高變化
 * @param {ElementDom} targetNode 需監(jiān)聽(tīng)的dom
 * @param {Function} throttleTime 監(jiān)聽(tīng)的頻率
 * @param {Number} callback 回調(diào)函數(shù)
 * @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、組件內(nèi)使用


<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 監(jiān)聽(tīng)容器寬高的變化
 */
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>
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容