vue实现视窗
Vue 实现视窗功能
Vue 可以通过多种方式实现视窗功能,包括监听窗口大小变化、全屏操作、模态框等。以下是几种常见的实现方法:
监听窗口大小变化
使用 window.addEventListener 监听 resize 事件,并在 Vue 组件中处理窗口大小变化:
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
}
}
}
实现全屏功能
通过 document.documentElement.requestFullscreen 方法实现全屏:
methods: {
toggleFullscreen() {
if (!document.fullscreenElement) {
document.documentElement.requestFullscreen()
} else {
if (document.exitFullscreen) {
document.exitFullscreen()
}
}
}
}
创建模态框
使用 Vue 组件实现模态框,通过 v-if 或 v-show 控制显示:
<template>
<div>
<button @click="showModal = true">打开模态框</button>
<div v-if="showModal" class="modal">
<div class="modal-content">
<span @click="showModal = false" class="close">×</span>
<p>模态框内容</p>
</div>
</div>
</div>
</template>
<script>
export default {
data() {
return {
showModal: false
}
}
}
</script>
<style>
.modal {
position: fixed;
z-index: 1;
left: 0;
top: 0;
width: 100%;
height: 100%;
background-color: rgba(0, 0, 0, 0.4);
}
.modal-content {
background-color: #fefefe;
margin: 15% auto;
padding: 20px;
width: 80%;
}
.close {
float: right;
cursor: pointer;
}
</style>
使用第三方库
对于更复杂的视窗功能,可以使用第三方库如 vue-window-size 或 vue-fullscreen:
安装 vue-window-size:
npm install vue-window-size
在 Vue 中使用:
import VueWindowSize from 'vue-window-size'
Vue.use(VueWindowSize)
export default {
computed: {
windowWidth() {
return this.$windowWidth
},
windowHeight() {
return this.$windowHeight
}
}
}
响应式布局
结合 CSS 媒体查询和 Vue 动态样式实现响应式布局:
<template>
<div :class="{'mobile-layout': isMobile}">
<!-- 内容 -->
</div>
</template>
<script>
export default {
computed: {
isMobile() {
return this.windowWidth < 768
}
}
}
</script>
<style>
.mobile-layout {
/* 移动端样式 */
}
</style>






