Vue3 引入路由 【Vue专栏】
作者:互联网
router.js文件
目录结构如下,注意这个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;
添加动态路由
import {useRouter} from "vue-router"; let router = useRouter(); function addRouter(){ router.addRoute( { path: "/vip", component: () => import("../views/VipPage.vue") }) }
或者:可以了解到,动态添加路由就是使用了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 }], })
欢迎关注作者微信公众号
标签:Vue,import,Vue3,component,path,addRoute,router,路由 来源: https://www.cnblogs.com/zhanqing/p/16684584.html