vue脚手架路由嵌套的使用

212 阅读2分钟

「这是我参与2022首次更文挑战的第8天,活动详情查看:2022首次更文挑战」。

子路由切换

router-view 是vue-router 提供的元素,专门用来当作占位符的。当我们不想跳转到新页面,只在当前页面切换着显示,那么就要涉及到路由的嵌套了。将来,路由规则匹配到的组件,就会展示到这个 router-view 中去 。

像在我们绘制登录页面的时候,通常会有一个链接跳转到注册页面,但是我们原本的登录页面上可能有一些登录和注册页面都有的内容,我们不希望重复写这段代码到两个页面,就可以将它们固定在页面上,不跳转页面,只改变点击登录或者注册时的内容即可

const routes = [
  { path: "/", redirect: "Home" },
  { path: '/home', name: 'Home', component: Home,
    children: [
      //在地址为空时,直接跳转Login路由
      {
        path:'',
        redirect: "login"
      },
      { path: 'login' , component: Login },
      { path: 'register' , component: Register }
  ]},
]

我们启动项目的第一个页面是{ path: "/", redirect: "Home" } Home页面,在 Home页面下使用children实现多层嵌套,同样在children下也可以实现重定向 { path:'', redirect: "login"} 这里要注意 子路由的路径前面,不要带/ ,否则永远以根路径开始请求。

<template>
<div id="app">
      <h1 style="color: yellow">不改变的内容</h1>
      <router-link to="/home/login">登录</router-link>
      <router-link to="/home/register">注册</router-link>
      <router-view></router-view>
</div>
</template>

在home页面中添加一个h1属性的黄颜色字体,在页面中充当不通过点击改变的导航栏部分,使用router-link(具有路由功能,原来的v-link指令)进行组件跳转,这里注意路由前面要加我们之前设置的home (/home/login)

login和register页面中的内容就是简单的字体( <h1>登录页面</h1>这种 )

最后效果大概就是这个样子了 1644320535781.gif

显示过渡动画

当路由切换的时候我们可以设置过渡动画

<transition name="" mode="out-in">
    <router-view></router-view>
</transition>
        .v-enter,
        .v-leave-to{
            opacity: 0;
            transform: translateX(100px);
        }
        .v-enter-active,
        .v-leave-active{
            transition: all 0.5s ease;
        }

命名视图

当我们需要将这两个组件同时显示在页面中时,我们可以采用命名视图实现

const routes = [
  { path: "/", redirect: "Home" },
  { path: '/home', name: 'Home', component: Home,
    children: [
      { 
        path : '', components: {
          'login': Login ,
          'register': Register         
        }
      }
  ]},
]
<div id="app">
      <h1 style="color: yellow">不改变的内容</h1>
      <div class="box">
        <router-view class="login_wrap" name="login"></router-view>
        <router-view class="register_wrap" name="register"></router-view>
      </div>
</div>
<style scoped lang='scss'>
  .box{
    display: flex;
    justify-content: space-between;
  }
  .login_wrap{
    width: 50%;
    background-color: antiquewhite;
  }
  .register_wrap{
    width: 50%;
    background-color: aquamarine;
  }
</style>

通过命名视图后我们使用 <router-view name="login"></router-view>的方式进行显示,然后用css进行简单的布局,左边登录,右边注册

效果: image.png