当前位置:首页 > VUE

vue项目 实现resize

2026-02-17 04:50:08VUE

实现 Vue 项目中的窗口或元素尺寸调整(Resize)

监听窗口大小变化

使用 window.addEventListener 监听 resize 事件,在组件挂载时添加监听,销毁时移除监听。以下是一个基础实现:

export default {
  data() {
    return {
      windowWidth: 0,
      windowHeight: 0
    }
  },
  mounted() {
    this.updateWindowSize()
    window.addEventListener('resize', this.updateWindowSize)
  },
  beforeDestroy() {
    window.removeEventListener('resize', this.updateWindowSize)
  },
  methods: {
    updateWindowSize() {
      this.windowWidth = window.innerWidth
      this.windowHeight = window.innerHeight
    }
  }
}

使用 ResizeObserver 监听元素尺寸变化

现代浏览器支持 ResizeObserver API,可高效监听特定 DOM 元素的尺寸变化:

vue项目 实现resize

export default {
  data() {
    return {
      elementWidth: 0,
      elementHeight: 0,
      resizeObserver: null
    }
  },
  mounted() {
    this.resizeObserver = new ResizeObserver(entries => {
      const entry = entries[0]
      this.elementWidth = entry.contentRect.width
      this.elementHeight = entry.contentRect.height
    })
    this.resizeObserver.observe(this.$el)
  },
  beforeDestroy() {
    this.resizeObserver.disconnect()
  }
}

使用第三方库(如 vue-resize)

安装 vue-resize 库可简化实现:

npm install vue-resize

组件中使用示例:

vue项目 实现resize

<template>
  <resize-observer @notify="handleResize" />
</template>

<script>
import { ResizeObserver } from 'vue-resize'

export default {
  components: { ResizeObserver },
  methods: {
    handleResize() {
      console.log('Element size changed')
    }
  }
}
</script>

防抖优化高频触发

对于高频触发的 resize 事件,建议添加防抖处理:

methods: {
  debounceResize: _.debounce(function() {
    console.log('Resize event with debounce')
  }, 200)
}

响应式设计结合 CSS

对于纯布局调整,可优先考虑 CSS 媒体查询:

@media (max-width: 768px) {
  .container {
    flex-direction: column;
  }
}

注意事项

  • 移动端需考虑 orientationchange 事件
  • 服务端渲染(SSR)环境下需做兼容处理
  • 复杂场景可结合 Vuex 管理全局尺寸状态
  • 性能敏感场景建议使用 requestAnimationFrame 优化

标签: 项目vue
分享给朋友:

相关文章

vue实现签名

vue实现签名

实现Vue签名功能的步骤 安装签名库 使用vue-signature库可以快速实现签名功能。通过npm或yarn安装: npm install vue-signature --save # 或 y…

vue实现本地数据存储

vue实现本地数据存储

使用 localStorage 或 sessionStorage Vue 中可以直接调用浏览器提供的 localStorage 或 sessionStorage API 进行数据存储。localSto…

vue设计与实现 书

vue设计与实现 书

vue设计与实现 书 《Vue.js设计与实现》是一本深入探讨Vue.js框架内部原理和设计思想的书籍,适合希望深入理解Vue.js的开发者。以下是关于这本书的详细信息: 书籍内容 《Vue.js…

vue实现生成二维码

vue实现生成二维码

使用qrcode.vue库生成二维码 安装qrcode.vue库: npm install qrcode.vue --save 在Vue组件中使用: <template> <…

vue实现iframe

vue实现iframe

Vue 中实现 iframe 的方法 在 Vue 项目中,可以通过多种方式实现 iframe 的嵌入。以下是几种常见的方法: 使用原生 HTML iframe 标签 直接在 Vue 组件的模板中使…

vue页面实现

vue页面实现

Vue 页面实现方法 创建 Vue 组件 使用 Vue 单文件组件(SFC)方式创建页面,文件扩展名为 .vue。一个基本的 Vue 组件包含三个部分:模板(template)、脚本(script)和…