foreword
We can put public components in App.vue, but sometimes we want a page that does not need to write public parts, so how do we set it up?
This article introduces three methods for introducing public components into some pages.
Method 1: Use sub-routing
-
Create a layout page to hold the common parts (header, footer, sidebar)
<!-- Layout --> <template> <div class=""> <el-container> <el-header></el-header> <el-container> <el-aside width="200px"></el-aside> <el-main><router-view /></el-main> </el-container> </el-container> </div> </template>
-
Add subroutes to pages that want to use the public part in router/index.js
export default new Router({ routes: [ { path: "/", component: Layout, redirect: "/dashboard", children: [ { name: "Dashboard", path: "dashboard", component: () => import("@/views/home/Index") } ] }, { name: "Login", path: "/login", component: () => import("@/views/login/index") } ] });
Method 2: Combining $route.meta
- in App.vue
<template>
<div id="app">
<div v-if="$route.meta.keepAlive">
<el-header></el-header>
<router-view></router-view>
</div>
<router-view v-if="!$route.meta.keepAlive"></router-view>
</div>
</template>
- Configure the meta.keepAlive value of public components in router.js to be true, otherwise it is false
{
path: '/home',
name: "Home",
component: Home,
meta: {
keepAlive: true
}
},
{
path: '/login',
name: "Login",
component: Login,
meta: {
keepAlive: false
}
},
Method 3: Use routing to determine whether to display
-
Use v-if in App.vue to judge whether the current route is displayed, and use watch to monitor the change of the route
<template> <div id="app"> <home-header v-if="!(path ==='/login') "></home-header> <home-aside v-if="!(path ==='/login')"></home-aside> <router-view/> </div> </template> <script> import HomeHeader from './components/header/Header' import HomeAside from './components/aside/Aside' export default { name: 'App', data(){ return{ path:'' } }, components: { HomeHeader, HomeAside, }, // 判断路由 mounted() { this.path = this.$route.path; // console.log(this.$route.path) }, watch:{ $route(to,from){ this.path = to.path } } } </script> <style> </style>