Home > Web Front-end > Vue.js > body text

How to dynamically add routing in vue3

WBOY
Release: 2023-05-17 23:22:16
forward
3790 people have browsed it

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;
Copy after login

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")
  })
}
Copy after login

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 }],
})
Copy after login

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!

Related labels:
source:yisu.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template