vue3.x教程:路由案例-重定向

提出问题

在 vue教程:路由案例 中,打开页面,不能默认显示 学生管理 或 教师管理,需要点击超链接才行,这是不完美的,如下图:

解决

添加一个 重定向 路由,如下:

{
    path: '/',
    redirect:'/student'
},

解释:当访问 / 时,重定向 到 /student 指定的组件

完整代码

修改 src/router/index.js 文件,内容如下:

// 引入
import {createRouter, createWebHashHistory} from 'vue-router'
//引入组件
import student from '@/views/Student.vue'
import teacher from '@/views/Teacher.vue'


// 创建路由器,需要传入 {} 对象
// (一个工程只需要创建一个路由器对象)
const router = createRouter({
    history: createWebHashHistory(), // 路由器的工作模式
    routes : [ // 注意:是 routes,不是router,其value是数组,数组里面的元素是 {} 对象
        {
            path: '/',
            redirect:'/student'
        },
        { 
            path: '/student', //路径,相当于<a>标签的href,关键:必须以 “/” 开头
            component: student //组件
        },
        { 
            path: '/teacher', //路径
            component: teacher //组件
        }
    ]
})


// 暴露路由,让其他页面可以使用
export default router

测试

打开浏览器,输入网址:http://localhost:5173/ ,敲回车,会自动跳转到 http://localhost:5173/#/student


原文出处:/show_1GW3maviTXt8.html