vue实现视窗
Vue 实现视窗的方法
在 Vue 中实现视窗功能通常涉及监听窗口大小变化、动态调整布局或组件显示。以下是几种常见的实现方式:
使用 window.addEventListener 监听视窗变化
在 Vue 组件的 mounted 生命周期钩子中添加事件监听器,监听窗口的 resize 事件:
export default {
data() {
return {
windowWidth: window.innerWidth
}
},
mounted() {
window.addEventListener('resize', this.handleResize)
},
beforeDestroy() {
window.removeEventListener('resize', this.handleResize)
},
methods: {
handleResize() {
this.windowWidth = window.innerWidth
}
}
}
使用 Vue 响应式数据实现动态布局
根据窗口宽度动态调整布局或显示不同的组件:

<template>
<div>
<component :is="currentComponent" />
</div>
</template>
<script>
export default {
computed: {
currentComponent() {
return this.windowWidth > 768 ? 'DesktopComponent' : 'MobileComponent'
}
}
}
</script>
使用 CSS 媒体查询与 Vue 结合
通过 CSS 媒体查询控制样式,同时在 Vue 中获取匹配状态:
export default {
data() {
return {
isMobile: false
}
},
created() {
const mediaQuery = window.matchMedia('(max-width: 768px)')
this.isMobile = mediaQuery.matches
mediaQuery.addListener((e) => {
this.isMobile = e.matches
})
}
}
使用第三方库(如 vue-responsive)
安装 vue-responsive 库可以更便捷地实现响应式功能:

import Vue from 'vue'
import VueResponsive from 'vue-responsive'
Vue.use(VueResponsive)
export default {
computed: {
device() {
return this.$responsive
}
}
}
视窗尺寸的实用工具函数
创建可复用的工具函数来检测视窗尺寸:
// utils/resize.js
export const getViewportSize = () => {
return {
width: window.innerWidth,
height: window.innerHeight
}
}
export const isMobileView = () => {
return window.innerWidth <= 768
}
在组件中使用:
import { getViewportSize, isMobileView } from '@/utils/resize'
export default {
data() {
return {
viewport: getViewportSize(),
isMobile: isMobileView()
}
}
}
注意事项
- 在组件销毁时务必移除事件监听器,避免内存泄漏。
- 对于频繁触发的
resize事件,建议使用防抖(debounce)优化性能。 - 考虑 SSR(服务端渲染)场景时,需要判断
window对象是否存在。
以上方法可以根据具体需求选择或组合使用,实现灵活的视窗响应功能。






