vue2.x教程:命名路由-(router-link标签、根据路由名字跳转)

提出问题

由 vue教程:嵌套路由(多级菜单)-(router-link标签、path跳转) 可知,当嵌套路由层级过深,<router-link> 的 to 属性值就会很长。

解决

使用 命名路由,可以解决上面的问题

给路由命名

修改 src/router/index.js 文件,给路由加上 name 属性,如下:

//引入VueRouter
import VueRouter from 'vue-router'
//引入组件
import student from '../views/Student'
import teacher from '../views/Teacher'
import exam from '../views/Exam'
import homework from '../views/Homework'

//创建路由,并暴露
export default new VueRouter({
    routes : [
        {
            path: '/',redirect:'/student'
        },
        { 
            path: '/student',
            component: student,
            children:[
                {
                    name: 'exam',//关键:路由名字
                    path: 'exam',
                    component: exam,
                },
                {
                    name: 'homework',//关键:路由名字
                    path: 'homework',
                    component: homework,
                }
            ]
        },
        { 
            path: '/teacher',
            component: teacher
        }
    ]
})

修改 Student.vue 文件

通过路由名字跳转,如下:

<router-link :to="{ name:'exam'}">考试管理</router-link>

关键部分是::to="{ name:'exam'}",写起来要简单些,不需要像 path那样,写完整路径

注意:

  • :to,要写上 :
  • exam是路由的 名字

注意:有时改完后可能不好使,需要重启服务

完整代码:

<template>
    <div class="app">
        <div>学生信息</div>
        <div>姓名:{{name}}</div>
        <div class="s1">
            <div class="menu">
                <h3>二级菜单</h3>
                <div>
                    关键:根据路由名字跳转
                    <router-link active-class="action" :to="{ name:'exam'}">考试管理</router-link>
                </div>
                <div>
                    根据路由的path跳转
                    <router-link active-class="action" to="/student/homework">作业管理</router-link>
                </div>
            </div>
            <router-view class="content"></router-view>
        </div>
    </div>
</template>
<script>
export default {
    data:function(){
        return {
            name:'李雷'
        }
    }
}
</script>
<style scoped>
.app{
    border: 1px red solid;
}
.action{
  color: red;
}
a{
  color: blue;
}
.s1{
    width: 500px;
    height:200px;
    margin:0 auto;
    /* border: 1px red solid; */
}
.menu{
    float: left;
}
.content{
    float:left;
    margin-left: 100px;
}
</style>

原文出处:/show_1IX2lEGHxOXT.html