import("../views/HomePage.v"/> import("../views/HomePage.v">
Home > Article > Web Front-end > How to dynamically add routing in vue3
Initialize the vite vue ts project and introduce vue-router.
The directory structure is as follows. Pay attention to this 404 redirect. Vue3 does not support directly using "*" to match all routes. You must use :catchAll(.*)
.
Initialization routing:
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;
Now if you access the vip route, you will jump to the 404 page.
If we need to access the vip page, we need to dynamically add the vip route. The following code implements itvip routing
Add:
import {useRouter} from "vue-router"; let router = useRouter(); function addRouter(){ router.addRoute( { path: "/vip", component: () => import("../views/VipPage.vue") }) }
At this time we will access the vip routing path:
can be accessed successfully .
By using the addRoute method of the router object, you can dynamically add routes. Sometimes you may add nested routes, which are sub-routes.
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 }], })
The above is the detailed content of How to dynamically add routing in vue3. For more information, please follow other related articles on the PHP Chinese website!