vue页面布局实现
Vue 页面布局实现方法
基础布局结构
使用 Vue 单文件组件(SFC)构建页面框架,结合 <template>、<script> 和 <style> 三个部分。布局通常通过 HTML 和 CSS 实现,Vue 负责动态数据绑定。
<template>
<div class="page-container">
<header class="header">头部导航</header>
<main class="main-content">
<aside class="sidebar">侧边栏</aside>
<section class="content">主内容区</section>
</main>
<footer class="footer">底部信息</footer>
</div>
</template>
<style scoped>
.page-container {
display: flex;
flex-direction: column;
min-height: 100vh;
}
.main-content {
display: flex;
flex: 1;
}
</style>
Flexbox 布局
Flexbox 是现代布局的核心方案,适合响应式设计。通过 display: flex 实现灵活排列。
/* 水平居中布局 */
.container {
display: flex;
justify-content: center;
align-items: center;
}
/* 等分布局 */
.item {
flex: 1; /* 均分剩余空间 */
}
Grid 布局
CSS Grid 适合复杂二维布局,可定义行和列的模板。
.grid-container {
display: grid;
grid-template-columns: 200px 1fr;
grid-gap: 20px;
}
.grid-sidebar {
grid-column: 1;
}
.grid-main {
grid-column: 2;
}
响应式设计
通过媒体查询适配不同屏幕尺寸,结合 Vue 的 v-if 或 v-show 控制元素显示。
@media (max-width: 768px) {
.main-content {
flex-direction: column;
}
.sidebar {
width: 100%;
}
}
使用 UI 框架
集成第三方库如 Element UI、Ant Design Vue 可快速实现布局:
<template>
<el-container>
<el-header>Header</el-header>
<el-main>Main</el-main>
<el-footer>Footer</el-footer>
</el-container>
</template>
<script>
import { ElContainer, ElHeader, ElMain, ElFooter } from 'element-plus'
</script>
动态布局切换
通过 Vue 的数据驱动特性实现布局变化:
<template>
<div :class="['layout', { 'vertical': isVertical }]">
<button @click="toggleLayout">切换布局</button>
</div>
</template>
<script>
export default {
data() {
return { isVertical: false }
},
methods: {
toggleLayout() {
this.isVertical = !this.isVertical
}
}
}
</script>
<style>
.layout {
display: flex;
flex-direction: row;
}
.layout.vertical {
flex-direction: column;
}
</style>
嵌套路由布局
利用 Vue Router 实现多层级布局结构:
const routes = [
{
path: '/',
component: MainLayout,
children: [
{ path: '', component: HomePage },
{ path: 'about', component: AboutPage }
]
}
]






