
Vue Router 官方文档https://router.vuejs.org/zh/introduction.html1. 安装 vue-routernpminstallvue-router2. 在src下的文件夹router下新建文件index.js、modules.jsindex.js基础配置/* src/router/index.js */import{createRouter,createWebHistory}fromvue-router;importroutesfrom./modules;// 创建路由实例constroutercreateRouter({history:createWebHistory(),// HTML5 历史模式routes,// 载入路由模块});// 全局导航守卫router.beforeEach((to,from){// 检查是否从外链携带 token 跳转而来if(to.query.token){localStorage.setItem(token,to.query.token);// 覆盖本地已有 tokenreturn{name:home,query:{},replace:true};// 跳转主页并清除参数继续导航守卫逻辑}// 检查 token 认证if(localStorage.getItem(token)){// 若已认证成功// 路由重定向if(to.namelogin){return{name:home};// 当前已登录状态却要去登录页强制跳转主页}elseif(...){return{...};// 其他重定向逻辑}else{returntrue;// 正常放行}}else{// 若未认证判断当前是否在登录页否则跳转登录if(to.name!login){return{name:login};// 避免循环跳转}else{returntrue;}}});exportdefaultrouter;modules.js路由模块/* src/router/modules.js */// import LoginView from ../views/LoginView.vue; // 若需强制优先打开的页面可以考虑静态导入exportdefault[{path:/login,// 路径会显示在浏览器 URL 中可能需要随时修改name:LoginView,// 名称推荐固定名称用于各项操作便于统一管理component:()import(../views/LoginView.vue),// 动态导入页面懒加载// component: LoginView, // 静态导入},{path:/,name:HomeView,component:()import(../views/HomeView.vue),redirect:{name:databoard},// 重定向非嵌套路由可以省略 component 配置// 嵌套子路由children:[{path:board,// 子路径将自动添加在上级路径后即显示为 /boardname:DataBoard,component:()import(../views/board/DataBoard.vue),// 路由元信息将任意自定义信息附加到路由上meta:{title:数据看板,// 标题icon:PieChart,// 图标requiresAuth:false,// 是否需要身份验证},},{path:user/:id,// 动态路由匹配导航时传参不同 id 都将渲染 UserCenter 页面示例/user/123name:UserCenter,component:()import(../views/user/UserCenter.vue),meta:{title:用户中心,icon:User,requiresAuth:true,},children:[{path:profile,// 匹配 /user/123/profilename:UserProfile,component:()import(../views/user/UserProfile.vue),meta:{title:个人资料,icon:,requiresAuth:true,},},{path:setting,// 匹配 /user/123/settingname:UserSetting,component:()import(../views/user/UserSetting.vue),meta:{title:账号设置,icon:,requiresAuth:true,},},],},],},// 捕获 404 Not found 路由必须书写在所有路由的最后{path:/:pathMatch(.*)*,name:NotFound,component:()import(../views/NotFound.vue),},];3. 在main.js中导入并注册路由/* src/main.js */import{createApp}fromvue;importAppfrom./App.vue;// 导入路由importrouterfrom./router;constappcreateApp(App);app.use(router);// 注册路由app.mount(#app);4. 在 vue 中渲染路由组件和对路由进行操作使用 ElementPlus 请参考我之前的文章vue3elementplussass/scss安装配置教程使用svg图标、引入外部字体、定义变量模块、修改组件样式、一键切换主题等App.vue根组件!-- src/App.vue --templaterouter-viewv-slot{ Component }transition!-- 可选在路由组件之间切换时实现过渡效果 --keep-alive!-- 可选非活跃的组件将会被缓存 --component:isComponent//keep-alive/transition/router-view/templateHomeView.vue嵌套路由上级组件!-- src/views/HomeView.vue --templatedivclasshome_view!-- 全局主菜单示例 --el-menu:default-activeactiveIndexroutertemplatev-foritem in menus:keyitem.name!-- router 模式下 index 需匹配路由 path --el-sub-menu:indexitem.pathv-ifitem.children?.filter(child child.meta.icon).lengthtemplate#titlecomponent:isitem.meta.icon/span{{ item.meta.title }}/span/templateel-menu-itemv-forchild in item.children:keychild.path:indexchild.path{{ child.meta.title }}/el-menu-item/el-sub-menuel-menu-item:indexitem.pathv-elsecomponent:isitem.meta.icon/template#title{{ item.meta.title }}/template/el-menu-item/template/el-menudivclasschild_page!-- 页面导航条示例 --el-breadcrumbel-breadcrumb-itemv-foritem in navs:keyitem.path:toitem.path{{ item.meta.title }}/el-breadcrumb-item/el-breadcrumb!-- 切换导航时若匹配到子路由其组件将渲染在这里 --router-view:key$route.path//div/div/templatescriptexportdefault{data(){return{activeIndex:this.$route.path,// 激活菜单自动匹配当前路径}},computed:{// 根据路由配置生成菜单列表menus(){// 递归整理路由树constfilterRoutes(data){constresult[]data.forEach(item{if(item.children?.length){constchildrenfilterRoutes(item.children)if(children?.length){result.push({...item,children})}}else{// 过滤需要授权但无权限的路由自定义逻辑if(!item.meta.requiresAuth||(item.meta.requiresAuthlocalStorage.getItem(item.name))){result.push(item)}}})returnresult}returnfilterRoutes(this.$router.options.routes[1].children)},// 根据路由记录生成导航列表navs(){returnthis.$route.matched.filter(itemitem.meta.title)}},watch:{// 监听路由更新$route(to,from){console.log(to,from)},// 监听路由参数变化$route.query:{handler(newVal,oldVal){console.log(newVal,oldVal)},deep:true,},},methods:{// 路由操作示例routerAction(){// 导航到路由this.$router.push({name:DataBoard})this.$router.replace({name:UserCenter})// replace 将替换历史记录this.$router.push({name:UserProfile,// 路径参数params:{id:321,// 匹配到 /user/321/profile},// 查询参数query:{page:1,// 显示为 /user/321/profile?page1},})// 返回上一个历史记录this.$router.back()this.$router.go(-1)// 获取路由数据constrouteNamethis.$route.nameconstuserIdthis.$route.params.idconstcurrentPagethis.$route.query.page},},}/script