想要让导航栏、侧边栏变为公共页面,则要在App.vue页面中加入。假设已经有了Header.vue和Left.vue,这里就不贴出来了,App.vue代码如下:
<template>
<div id="app">
<!-- 其他页 -->
<el-container >
<el-header>
<!-- 导航栏 -->
<header-nav></header-nav>
</el-header>
<el-container>
<el-aside width="250px">
<!-- 侧边栏 -->
<left></left>
</el-aside>
<el-main>
<!-- Body -->
<router-view></router-view>
</el-main>
</el-container>
</el-container>
<!-- 登录页 -->
<router-view ></router-view>
</div>
</template>
<script>
import header from './components/Header.vue';
import left from './components/Left.vue';
export default{
components: {
headerNav: header,
left: left
}
}
</script>
<style>
</style>
此时运行会发现,所有的页面都被加上了这两个公共页面,而实际场景中,我们往往希望登录页是不需要导航栏和侧边栏的,那么就需要规避掉登录页。
这时,就可以采用keep-alive结合$route.meta来实现这个功能。keep-alive 是 Vue 内置的一个组件,可以使被包含的组件保留状态,或避免重新渲染。$route.meta则可以选择让需要的页面才展示。修改App.vue,如下:
<template>
<div id="app">
<!-- 其他页 -->
<el-container v-if="$route.meta.keepAlive">
<el-header>
<keep-alive>
<!-- 导航栏 -->
<header-nav></header-nav>
</keep-alive>
</el-header>
<el-container>
<el-aside width="250px">
<!-- 侧边栏 -->
<keep-alive>
<left></left>
</keep-alive>
</el-aside>
<el-main>
<!-- Body -->
<router-view></router-view>
</el-main>
</el-container>
</el-container>
<!-- 登录页 -->
<router-view v-if="!$route.meta.keepAlive"></router-view>
</div>
</template>
<script>
import header from './components/Header.vue';
import left from './components/Left.vue';
export default{
components: {
headerNav: header,
left: left
}
}
</script>
<style>
</style>
index.js代码如下:
import Vue from 'vue'
import Router from 'vue-router'
import HelloWorld from '@/components/HelloWorld'
import Login from '@/views/Login'
import index from '@/views/index'
import versionList from '@/views/versionList'
Vue.use(Router)
export default new Router({
routes: [
{
path: '/',
name: 'login',
component: Login,
meta: {
keepAlive: false
}
},
{
path: '/index',
name: 'index',
component: index,
meta: {
keepAlive: true
}
},
{
path: '/versionList',
name: 'versionList',
component: versionList,
meta: {
keepAlive: true
}
},
]
})
通过设置keepAlive的值就可以实现除了登录页不展示公共页面,在其他页面均展示的功能。