美文网首页
vue3 监听页面元素变化

vue3 监听页面元素变化

作者: ThisWu | 来源:发表于2024-02-03 16:14 被阅读0次

    引用于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 监听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>
    

    相关文章

      网友评论

          本文标题:vue3 监听页面元素变化

          本文链接:https://www.haomeiwen.com/subject/xlexadtx.html