乐趣区

关于vue.js:vue中实现部分页面引入公共组件

前言

咱们能够把公共组件放到 App.vue 中,然而有时候咱们心愿某个页面不须要这写公共局部,那么须要怎么设置呢?

本文为大家介绍三种局部页面引入公共组件的办法。

办法一:利用子路由

  • 创立一个 layout 页面来寄存公共局部(页头、页脚、侧边栏)

    <!-- 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>
  • 在 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")
        }
      ]
    });
    

办法二:联合 $route.meta

  • 在 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>
  • 在 router.js 中配置想要显示公共组件的 meta.keepAlive 值为 true,反之则是 false
{
      path: '/home',
      name: "Home",
      component: Home,
      meta: {keepAlive: true}
},
{
      path: '/login',
      name: "Login",
      component: Login,
      meta: {keepAlive: false}
},

形式三:利用路由判断是否显示

  • 在 App.vue 中利用 v -if 判断以后路由是否显示,并用 watch 来监听路由的扭转

    <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>
退出移动版