import("../views/HomePage.v"/> import("../views/HomePage.v">

Home >Web Front-end >Vue.js >How to dynamically add routing in vue3

How to dynamically add routing in vue3

WBOY
WBOYforward
2023-05-17 23:22:163823browse

1. Initialize the project

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(.*).

How to dynamically add routing in vue3

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.

How to dynamically add routing in vue3

2. Add "vip" route

If we need to access the vip page, we need to dynamically add the vip route. The following code implements itvip routingAdd:

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:

How to dynamically add routing in vue3

can be accessed successfully .

3. Summary

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!

Statement:
This article is reproduced at:yisu.com. If there is any infringement, please contact admin@php.cn delete