vue实现上下布局
实现上下布局的基本结构
在Vue中实现上下布局通常需要使用CSS的flexbox或grid布局方式。以下是一个基础的上下布局实现示例:
<template>
<div class="layout">
<header class="header">顶部区域</header>
<main class="content">主要内容区域</main>
</div>
</template>
<style scoped>
.layout {
display: flex;
flex-direction: column;
height: 100vh;
}
.header {
height: 60px;
background-color: #f0f0f0;
}
.content {
flex: 1;
overflow: auto;
}
</style>
使用CSS Grid实现
CSS Grid提供了另一种实现方式,可以更灵活地控制布局:
<template>
<div class="grid-layout">
<header class="header">顶部区域</header>
<main class="content">主要内容区域</main>
</div>
</template>
<style scoped>
.grid-layout {
display: grid;
grid-template-rows: 60px 1fr;
height: 100vh;
}
.header {
background-color: #f0f0f0;
}
.content {
overflow: auto;
}
</style>
响应式布局处理
为了在不同屏幕尺寸下保持良好的显示效果,可以添加媒体查询:

@media (max-width: 768px) {
.header {
height: 50px;
}
}
固定顶部和滚动内容
如果需要顶部固定而内容区域可滚动,可以这样实现:
.layout {
display: flex;
flex-direction: column;
height: 100vh;
}
.header {
position: sticky;
top: 0;
z-index: 100;
}
.content {
flex: 1;
overflow-y: auto;
}
使用Vue组件化结构
将布局拆分为可复用的组件:

<template>
<VerticalLayout>
<template #header>
<AppHeader />
</template>
<template #content>
<RouterView />
</template>
</VerticalLayout>
</template>
创建VerticalLayout组件:
<template>
<div class="vertical-layout">
<div class="header">
<slot name="header"></slot>
</div>
<div class="content">
<slot name="content"></slot>
</div>
</div>
</template>
动态高度调整
如果需要根据内容动态调整高度,可以使用计算属性:
export default {
computed: {
headerHeight() {
return this.$refs.header?.clientHeight || 60
}
}
}
然后在样式中使用:
.layout {
grid-template-rows: v-bind('headerHeight + "px"') 1fr;
}






