vue实现视窗
Vue 实现视窗功能
在 Vue 中实现视窗功能通常涉及监听浏览器窗口大小变化、响应式布局或创建自定义弹窗组件。以下是几种常见实现方式:
监听浏览器窗口大小变化
使用 Vue 的 mounted 和 beforeDestroy 生命周期钩子监听 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
}
}
}
响应式布局结合 CSS
利用 CSS 媒体查询与 Vue 的响应式数据结合实现视窗适配:
/* 在样式文件中定义 */
@media (max-width: 768px) {
.container {
flex-direction: column;
}
}
在组件中动态切换样式类:

export default {
computed: {
isMobile() {
return this.windowWidth < 768
}
},
template: `
<div :class="{ 'mobile-layout': isMobile }">
<!-- 内容 -->
</div>
`
}
自定义弹窗组件
创建可复用的视窗弹窗组件:
// PopupWindow.vue
<template>
<div class="overlay" v-if="visible" @click.self="close">
<div class="popup">
<slot></slot>
<button @click="close">关闭</button>
</div>
</div>
</template>
<script>
export default {
props: ['visible'],
methods: {
close() {
this.$emit('update:visible', false)
}
}
}
</script>
使用该组件:

<template>
<button @click="showPopup = true">打开视窗</button>
<PopupWindow v-model="showPopup">
<h2>自定义内容</h2>
</PopupWindow>
</template>
<script>
import PopupWindow from './PopupWindow.vue'
export default {
components: { PopupWindow },
data() {
return {
showPopup: false
}
}
}
</script>
第三方库集成
对于复杂需求,可以使用专门库如:
-
vue-window-size:简化窗口尺寸监听
import { useWindowSize } from 'vue-window-size' export default { setup() { const { width, height } = useWindowSize() return { width, height } } } -
vue-js-modal:提供功能丰富的模态框
import VModal from 'vue-js-modal' Vue.use(VModal) // 使用 this.$modal.show('my-modal')
注意事项
- 移动端适配需考虑
viewport元标签:<meta name="viewport" content="width=device-width, initial-scale=1.0"> - 频繁的
resize事件应使用防抖优化性能 - 弹窗组件应处理好
z-index层级和滚动锁定






