vue 动态拼接路由 完整简洁

310 阅读1分钟

router

import Vue from "vue";import Router from "vue-router";import Home from "@/pages/Home/home.vue";import jgcx from "@/pages/jgcx/jgcx.vue";import zxts from "@/pages/zxts/zxts.vue";import notice from "@/pages/notice/notice.vue";import noticeList from "@/pages/notice/noticeList.vue";import noticeDetails from "@/pages/notice/noticeDetails.vue";import iframe from "@/pages/iframe/iframe.vue";// 获取路由数据import { getnavigation } from '@/api/apiList.js'import { store } from "@/store/store.js";const originalPush = Router.prototype.push;Router.prototype.push = function push(location) {  return originalPush.call(this, location).catch((err) => err);};Vue.use(Router);const routes = [  {    name: "iframe",    path: "/iframe",    component: iframe,  },]// 实例化 Router 对象const router = new Router({  // linkActiveClass:'selected',  routes  // mode: 'history'})// 路由拦截 在跳转之前router.beforeEach((to, from, next) => {
调用拼接路由方法  addData()  next()})function addData() {  // 请求接口 路由数据  getnavigation().then(res => {    if (res.code == "200") {      let navData = res.data.records      let eventPath = navData[0].jumpUrl.split('#')[1].split('?')[0]      sessionStorage.setItem("eventPath",eventPath)      // 拼接路由 根据自己获取到的数据灵活应用      navData.forEach((item, index) => {        let url2 = item.jumpUrl        if (url2.split('#')[1]) {          let path = url2.split('#')[1].split('?')[0]
          router.addRoute 添加路由
          router.addRoute({            path: path,            name: path,            component: () => import('../pages/notice' + path)          })        }      })    }  })}export default router