前面我们已经写好了登录页面,当正常登录后应该跳转到首页
我们的顶部导航栏和左侧导航栏一般是固定的,我们可以布局成下面的样式

因为我们的首页是个公共的组件,点击会员管理,供应商管理都不会变,所以我们可以放在components 下面,在下面创建一个 Layout.vue 的文件,写入如下内容
<template> <div> <div class="header">头部</div> <div class="navbar">左侧区域</div> <div class="main">主区域</div> </div> </template>
然后再router下的index.js里导入路由,新增了第七行和19,20,21行
1 import Vue from "vue"; 2 import Router from "vue-router"; 3 // import Login from ‘@/views/login/index‘ 4 5 // 下面的情况,默认会导入@/views/login下的index.vue组件 6 import Login from ‘@/views/login‘ 7 import Layout from ‘@/components/Layout‘ 8 Vue.use(Router); 9 10 11 export default new Router({ 12 routes: [ 13 { 14 path: ‘/login‘, 15 name: ‘login‘, // 路由名称 16 component: Login // 组件对象 17 }, 18 { 19 path: ‘/‘, 20 name: ‘layout‘, // 路由名称 21 component: Layout // 组件对象 22 }, 23 24 ] 25 });
然后我们正常登录,就可以看到首页了

这样当然是很难看的,我们可以在上面的基础上写上面和左边的导航栏
在 Layout.vue下实现头部样式,左侧样式,主区域,代码如下
<template>
<div>
<div class="header">头部</div>
<div class="navbar">左侧区域</div>
<div class="main">主区域</div>
</div>
</template>
<style scoped>
/* 头部样式 */
.header {
position: absolute;
line-height: 50px;
top: 0px;
left: 0px;
right: 0px;
background-color: #2d3a4b;
}
/* 左侧样式 */
.navbar {
position: absolute;
width: 230px;
top: 50px; /* 距离上面50像素 */
left: 0px;
bottom: 0px;
overflow-y: auto; /* 当内容过多时y轴出现滚动条 */
background-color: #545c64;
}
/* 主区域 */
.main {
position: absolute;
top: 50px;
left: 230px;
bottom: 0px;
right: 0px; /* 距离右边0像素 */
padding: 10px;
overflow-y: auto; /* 当内容过多时y轴出现滚动条 */
/* background-color: red; */
}
</style>
重新访问页面,布局如下

主区域,左侧区域,头部区域,我们不可能都放在 Layout.vue 里面,这样代码就显得冗余了,可以在 components 下面新建三个文件夹,分别为 AppHeader,Appmain,Appnavbar,里面各键一个index.vue 文件,如下,Appmain下的 Link.vue 先不用管它

然后我们把 Layout.vue 里的下面三行代码抽取出来放到对应的index.vue里面
<div class="header">头部</div> <div class="navbar">左侧区域</div> <div class="main">主区域</div>
例如AppHeader下的index.vue里面
<template> <div class="header">头部</div> </template>

这样我们提取出来了,需要在Layout下引用,代码如下
<template>
<div>
<!-- 使用子组件,使用-,不建议使用驼峰 -->
<app-header></app-header>
<app-navbar></app-navbar>
<app-main></app-main>
</div>
</template>
<script>
// 会导入./AppHeader下面的index.vue组件
import AppHeader from "./AppHeader"
import AppNavbar from "./AppNavbar"
import AppMain from "./AppMain"
// 导入子组件,缩写格式 AppHeader: AppHeader
export default {
components: { AppHeader, AppNavbar, AppMain } // 有s
};
</script>
<style scoped>
/* 头部样式 */
.header {
position: absolute;
line-height: 50px;
top: 0px;
left: 0px;
right: 0px;
background-color: #2d3a4b;
}
/* 左侧样式 */
.navbar {
position: absolute;
width: 230px;
top: 50px; /* 距离上面50像素 */
left: 0px;
bottom: 0px;
overflow-y: auto; /* 当内容过多时y轴出现滚动条 */
background-color: #545c64;
}
/* 主区域 */
.main {
position: absolute;
top: 50px;
left: 230px;
bottom: 0px;
right: 0px; /* 距离右边0像素 */
padding: 10px;
overflow-y: auto; /* 当内容过多时y轴出现滚动条 */
/* background-color: red; */
}
</style>
刷新我们的页面,页面还是之前的样式,则我们的抽取没有问题
原文:https://www.cnblogs.com/zouzou-busy/p/13080665.html