vue实现屏幕撑满
使用 CSS 设置全屏
在 Vue 中实现屏幕撑满可以通过 CSS 样式来控制。确保根元素和子元素的高度设置为 100%。
<template>
<div class="full-screen">
<!-- 内容 -->
</div>
</template>
<style>
html, body {
height: 100%;
margin: 0;
padding: 0;
}
.full-screen {
height: 100vh;
width: 100vw;
}
</style>
使用 Flexbox 布局
Flexbox 可以轻松实现全屏布局,适合动态内容或需要居中的场景。
<template>
<div class="flex-container">
<div class="content">
<!-- 内容 -->
</div>
</div>
</template>
<style>
html, body {
height: 100%;
margin: 0;
padding: 0;
}
.flex-container {
display: flex;
min-height: 100vh;
width: 100%;
}
.content {
flex: 1;
}
</style>
使用 Grid 布局
CSS Grid 提供了更灵活的布局方式,适合复杂全屏设计。
<template>
<div class="grid-container">
<!-- 内容 -->
</div>
</template>
<style>
html, body {
height: 100%;
margin: 0;
padding: 0;
}
.grid-container {
display: grid;
min-height: 100vh;
width: 100%;
}
</style>
动态计算高度
如果需要考虑导航栏或其他固定高度的元素,可以通过 JavaScript 动态计算剩余高度。
<template>
<div ref="container" class="dynamic-height">
<!-- 内容 -->
</div>
</template>
<script>
export default {
mounted() {
this.adjustHeight();
window.addEventListener('resize', this.adjustHeight);
},
beforeDestroy() {
window.removeEventListener('resize', this.adjustHeight);
},
methods: {
adjustHeight() {
const navbarHeight = 60; // 假设导航栏高度为 60px
this.$refs.container.style.height = `${window.innerHeight - navbarHeight}px`;
}
}
};
</script>
<style>
.dynamic-height {
width: 100%;
overflow: auto;
}
</style>
使用 Vue 组件库
如果使用 UI 组件库如 Element UI 或 Vuetify,可以直接使用其提供的全屏布局组件。
<template>
<v-app>
<v-main>
<!-- 内容 -->
</v-main>
</v-app>
</template>
<script>
import { VApp, VMain } from 'vuetify/lib';
export default {
components: {
VApp,
VMain
}
};
</script>
响应式设计考虑
确保全屏布局在不同设备上都能正常显示,可以通过媒体查询调整样式。
@media (max-width: 768px) {
.full-screen {
height: auto;
min-height: 100vh;
}
}






