学习笔记Vue(十 八)—— 嵌套路由

延续之前的路由,如果我想在student模块里再加一个路由链接到具体的某个学生的信息,就要使用嵌套路由。
例如:
在这里插入图片描述
第一步:
在student路由里加一个children属性,用来配置子路由,
children里的写法和正常配置路由一样,也是有path,name,component,
不同的是子路由的path可以直接写一个名,例如amy,在页面上的路由就会加上他的父级,显示成:/student/amy

 {
      path: '/student',
      name: 'student',
      component: ()=>{
        return import('./views/Student');
      },
      redirect: '/student/amy',
      children: [
        {
          path: "amy",
          name: 'amy',
          component: () => import('./views/Amy')
        },
        {
          path: "simon",
          name: 'simon',
          component: () => import('./views/Simon')
        },
        {
          path: "adam",
          name: 'adam',
          component: () => import('./views/Adam')
        }
      ]
    },

redirect属性是当你进入这个路由的时候重定向地址,直接指定到一个默认显示的页面,一般还可以这样配置:

    //path是* 就是没有这个路由路径存在的时候,
    //to.path 是你当前的路径,如果是/,就定位到主页
    {
      path: '*',
      redirect (to) {
        if(to.path === '/'){
          return '/home'
        }
      }
    }

然后子路由一样把页面放到views文件夹里,页面级的components都放在views文件夹下,普通的小组件放在components文件夹里。
举例:
Amy.vue

<template>
    <h2> 这是amy的界面 </h2>
</template>

要想点击跳转,同样也需要router-link和router-view ,写在student.vue里,
注意,在一个组件里写<router-link>和<router-view>标签,要在最外面用一个div包一下,不能直接写在template标签里,不然会报一个错误:Component template should contain exactly one root element.

<template>
    <div>
        <h4 class="student">学员展示</h4>
        <ul>
            <router-link tag='li' to="/student/amy">Amy</router-link>
            <router-link tag='li' to="/student/simon">Simon</router-link>
            <router-link tag='li' to="/student/adam">Adam</router-link>
        </ul>
        <router-view></router-view>
    </div>
</template>

<style scoped>
    ul{
        text-align: center;
    }
    ul li{
        display: inline-block;
        padding: 5px ;
        cursor: pointer;
    }
    ul li:hover{
        border-bottom: 1px solid black;
    }
</style>

如果不用router-link标签,还有一种方式可以实现点击跳转路由,通过@click点击事件,和$router来实现:

//template
<h1 @click="handleClick">点击跳转至首页</h1>
//script:
export default {
    methods: {
      handleClick (){
        // push 和 replace 的区别   
        //push  页面队列:[a, b, c, d]  => [a, b, c, d, e]
        //replace  [a, b, c, d]  =>  [a, b, c, e]   页面回退返回上一个的时候不同。
        // this.$router.push('/home');
        this.$router.replace('/home');

        this.$router.go(-1);  //页面像前走几步, -1 后退一步 
      }
    }
  }

this.$router.push 和 this.$router.replace都能实现路由的跳转,他们的区别是,push实在页面队列里加一个页面,而replace是把你当前的页面替换掉了,所以在页面回退的时候他们的表现是不同的。
还有一个$router.go() 里面穿的值是代表页面走几步,如果是-1,就向后退一步,以此类推。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值