在Vue3项目中安装路由
第一步:执行npm
命令安装路由
npm install vue-router@4
第二步:在项目的src
文件夹下创建router
子文件夹
第三步:创建index.js
和routes.js
文件,以下为文件的代码
//通过vue-router插件实现模板路由配置
import { createRouter, createWebHashHistory } from 'vue-router'
import { constantRoute } from './routes'
//创建路由器
let router = createRouter({
//路由模式hash
history: createWebHashHistory(),
routes: constantRoute,
//滚动行为
scrollBehavior() {
return {
left: 0,
top: 0,
}
},
})
export default router
//对外暴露配置路由(常量路由)
export const constantRoute = [
{
path: '/',
redirect: '/login',
name: 'Default'
},
{
path: '/login',
component: () => import('@/views/Login.vue'),
name: 'Login'
},
{
path: '/index',
component: () => import('@/views/Index.vue'),
name: 'Index'
},
{
path: '/course',
component: () => import('@/components/Layout.vue'),
name: 'Course',
children: [
{
path: 'list',
component: () => import('@/views/course/CourseList.vue'),
name: 'CourseList'
},
{
path: 'info',
component: () => import('@/views/course/CourseInfo.vue'),
name: 'CourseInfo'
},
{
path: 'play',
component: () => import('@/views/course/CoursePlay.vue'),
name: 'CoursePlay'
},
]
},
{
path: '/teacher',
component: () => import('@/components/Layout.vue'),
name: 'Teacher',
children: [
{
path: 'list',
component: () => import('@/views/teacher/TeacherList.vue'),
name: 'TeacherList'
},
{
path: 'info',
component: () => import('@/views/teacher/TeacherInfo.vue'),
name: 'TeacherInfo'
},
]
},
{
path: '/article',
component: () => import('@/components/Layout.vue'),
name: 'Article',
children: [
{
path: 'list',
component: () => import('@/views/article/ArticleList.vue'),
name: 'ArticleList'
},
{
path: 'info',
component: () => import('@/views/article/ArticleInfo.vue'),
name: 'ArticleInfo'
},
]
},
{
path: '/user',
component: () => import('@/components/Layout.vue'),
name: 'User',
children: [
{
path: 'center',
component: () => import('@/views/user/UserCenter.vue'),
name: 'UserCenter'
},
]
},
{
path: '/404',
component: () => import('@/views/404.vue'),
name: '404'
},
{
path: '/:pathMatch(.*)*',
redirect: '/404',
name: 'Any'
}
]
第四步:引入路由,让路由进行工作
import router from './router'
app.use(router)
第四步的完整代码:
// main.js
import { createApp } from 'vue'
import App from './App.vue'
import router from './router'
const app = createApp(App)
app.use(router)
app.mount('#app')