vue实现视窗
Vue 实现视窗功能
在 Vue 中实现视窗功能通常涉及监听浏览器窗口大小变化、管理视窗状态或创建自定义视窗组件。以下是几种常见实现方式:
监听窗口大小变化
通过 window.addEventListener 监听 resize 事件,并在组件销毁时移除监听:
export default {
data() {
return {
windowWidth: window.innerWidth,
windowHeight: window.innerHeight
}
},
mounted() {
window.addEventListener('resize', this.handleResize)
},
beforeDestroy() {
window.removeEventListener('resize', this.handleResize)
},
methods: {
handleResize() {
this.windowWidth = window.innerWidth
this.windowHeight = window.innerHeight
}
}
}
使用 Vue 响应式特性
结合 Vue.observable 创建全局响应式视窗对象:
// store/window.js
import Vue from 'vue'
export const windowStore = Vue.observable({
width: window.innerWidth,
height: window.innerHeight
})
window.addEventListener('resize', () => {
windowStore.width = window.innerWidth
windowStore.height = window.innerHeight
})
自定义视窗组件
创建可复用的视窗组件,提供插槽和响应式尺寸:
<template>
<div class="viewport" :style="style">
<slot :width="width" :height="height"></slot>
</div>
</template>
<script>
export default {
data() {
return {
width: window.innerWidth,
height: window.innerHeight
}
},
computed: {
style() {
return {
width: `${this.width}px`,
height: `${this.height}px`
}
}
},
mounted() {
window.addEventListener('resize', this.updateDimensions)
},
destroyed() {
window.removeEventListener('resize', this.updateDimensions)
},
methods: {
updateDimensions() {
this.width = window.innerWidth
this.height = window.innerHeight
}
}
}
</script>
使用第三方库
考虑使用专门处理视窗的库如 vue-resize 或 vue-window-size:
// 使用 vue-window-size
import Vue from 'vue'
import VueWindowSize from 'vue-window-size'
Vue.use(VueWindowSize)
// 组件内直接使用
this.$windowWidth
this.$windowHeight
响应式设计辅助
结合 CSS 媒体查询和 Vue 数据实现响应式布局:
<template>
<div :class="['container', screenSize]">
<!-- 内容 -->
</div>
</template>
<script>
export default {
computed: {
screenSize() {
if (this.windowWidth < 768) return 'mobile'
if (this.windowWidth < 1024) return 'tablet'
return 'desktop'
}
}
}
</script>
视窗上下文提供
通过 provide/inject 跨组件共享视窗尺寸:

// 根组件
export default {
provide() {
return {
windowSize: {
width: this.windowWidth,
height: this.windowHeight
}
}
}
}
// 子组件
export default {
inject: ['windowSize']
}
每种方法适用于不同场景,可根据项目需求选择简单监听、全局状态管理或完整组件解决方案。对于复杂应用,推荐使用 Vuex 配合窗口尺寸监听实现统一状态管理。






