Vue配置路由是Vue开发中非常关键的一环,它负责定义URL到组件的映射关系,使得用户可以通过改变URL来访问不同的页面组件,而无需重新加载整个页面。
路由文件
在src目录下有一个router的文件夹,其中有一个index.js
文件。这个文件将用于定义和导出路由配置。
引入相关依赖
在index.js
文件中,需要引入Vue、VueRouter以及需要被路由的组件。
import { createRouter, createWebHistory } from 'vue-router';
import Home from '../views/Home.vue';
import About from '../views/About.vue';
定义路由
每个路由对象都应该包含path
(路由路径)和component
(对应的组件)
const router = createRouter({
history: createWebHistory(import.meta.env.BASE_URL),
routes: [
{
path:'/',
component:Layout,
children:[{
path:'',
component:Home
},{
path:'/exams',
component:Exams
},{
path:'/idu',
component:Introduction
}]
},{
path:'/login',
component:Login
}
]
})
创建router实例
使用createRouter
函数和之前定义的路由数组来创建router实例。Vue 3中推荐使用createWebHistory
来设置history模式。
const router = createRouter({
history: createWebHistory(),
routes
});
导出router实例
export default router;