1、安装
pnpm i vue-router
2、新建文件:src/routes.ts
import { RouteRecordRaw } from 'vue-router'
export const constantRoute: RouteRecordRaw[] = [
{
//
path: '/',
redirect: '/login',
},
{
//
path: '/login',
component: () => import('@/views/Login/index.vue'),
name: 'Login',
meta: {
title: '登录',
},
},
{
//登录成功展示数据的页面 main.vue
path: '/layout',
component: () => import('@/layout/index.vue'),
name: 'layout',
meta: {
title: 'layout',
},
},
{
path: '/404',
component: () => import('@/views/404/index.vue'),
name: '404',
meta: {
title: '404',
},
},
{
// 任意路由(无效或者不存在的路径 跳转至404)
path: '/:pathMatch(.*)*',
component: () => import('@/views/404/index.vue'),
name: 'Any',
meta: {
title: '任意',
},
},
]
3、新建文件:src/index.ts
import { createRouter, createWebHashHistory } from 'vue-router'
import { constantRoute } from './routes'
const router = createRouter({
history: createWebHashHistory(),
routes: constantRoute,
// 滚动行为
scrollBehavior() {
// ...
return {
left: 0,
top: 0,
}
},
})
export const setupRouter = (app: any) => {
app.use(router)
}
export default router
4、main.ts 引入
// 路由
import { setupRouter } from './router'
// 创建实例
const setupAll = async () => {
const app = createApp(App)
await setupRouter(app)
app.mount('#app')
}
setupAll()
5、app.vue 中加入代码
以上完成 ,输入不同路径就可以跳转到对应页面了。