目录结构如下,注意这个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路由,下面代码实现了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怎么动态添加路由的详细内容。