Vue Router官网:router.vuejs.org/
一、安装Vue Router
使用pnpm包管理器进行安装。
pnpm add vue-router@4
二、创建并配置路由
1、创建必需的基础路由组件
Vue3项目至少有4个必需的基础路由组件:
- 登录路由组件
- 首页路由组件
- 404路由组件
- 除了上述组件的任一路由组件
- 在src文件夹下创建views文件夹,该文件夹下放置所有的路由组件。
- 在views文件夹下,创建路由组件
- /views/login/index.vue 登录路由组件
- /views/home/index.vue 首页路由组件
- /views/404/index.vue 404路由组件
2、创建路由器并配置路由
- 在src文件夹下新建文件router/routes.ts,该文件中配置了项目所有的路由。
// routes.ts
// 对外暴露配置路由
export const constantRoutes = [
// 登录
{
path: '/login',
name: 'login', // 命名路由
component: () => import('@/views/login/index.vue')
},
// 登录成功以后展示数据
{
path: '/',
name: 'layout', // 命名路由
component: () => import('@/views/home/index.vue')
},
// 404
{
path: '/404',
name: '404', // 命名路由
component: () => import('@/views/404/index.vue')
},
// 除了上面三个路由以外的任一路由
{
path: '/:pathMatch(.*)*',
redirect: '/404',
name: 'any'
}
]
- 在src文件夹下新建文件router/index.ts,该文件中创建路由器并进行配置。
// router/index.ts
// 通过vue-router插件实现模板路由的配置
import { createRouter, createWebHashHistory } from 'vue-router'
import { constantRoutes } from './routes'
// 创建路由器
const router = createRouter({
// 路由模式hash
history: createWebHashHistory(),
routes: constantRoutes,
// 页面中滚动条的滚动行为,默认靠上靠左
scrollBehavior() {
return {
left: 0,
top: 0
}
}
})
export default router
3、项目中注册路由器
在main.ts文件中注册路由器。
// main.ts
// 引入路由
import router from '@/router'
import App from '@/App.vue'
const app = createApp(App)
// 注册模板路由
app.use(router)
app.mount('#app')
三、展示路由组件
使用RouterView组件展示路由组件。
比如在App.vue组件中展示。
// App.vue
<template>
<router-view></router-view>
</template>
<script setup lang="ts" name=""></script>
<style lang="scss" scoped></style>