初始化vite + vue + ts项目,引入vue-router。
目录结构如下,注意这个404重定向,vue3不支持直接使用“*”匹配所有路由了,要使用:catchall(.*)。

初始化路由:
import {createRouter, createWebHashHistory} from "vue-router";
const routes = [
{
path: "/",
component: () => import("../views/HomePage.vue")
},
{
path: "/404",
component: () => import("../views/ErrorPage.vue")
},
{
path: "/:catchAll(.*)", // 不识别的path自动匹配404
redirect: '/404',
},
]
const router=createRouter({
history: createWebHashHistory(),
routes
})
export default router;现在如果去访问vip路由,则会跳转到404页面。

立即学习“前端免费学习笔记(深入)”;
如果需要访问vip页面,那么就需要我们动态地添加vip路由,下面代码实现了vip路由添加:
import {useRouter} from "vue-router";
let router = useRouter();
function addRouter(){
router.addRoute( {
path: "/vip",
component: () => import("../views/VipPage.vue")
})
}此时我们再去访问vip路由路径:

可以成功访问了。
通过使用router对象的addRoute方法,可以实现动态添加路由。有时候可能是添加嵌套路由,也就是子路由。
router.addRoute({ name: 'admin', path: '/admin', component: Admin })
router.addRoute('admin', { path: 'settings', component: AdminSettings })
// 这等效于:
router.addRoute({
name: 'admin',
path: '/admin',
component: Admin,
children: [{ path: 'settings', component: AdminSettings }],
})以上就是vue3怎么动态添加路由的详细内容,更多请关注php中文网其它相关文章!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号