vue vue-router接口动态路由

const express = require('express')
const app = express()
const cors = require('cors')

app.use(cors())

app.get("/api", (req, res) => {
  const retStruct = [
    {
      path: '/demo',
      name: 'Demo',
      meta: {
        title: '测试demo标题',
        keepAlive: true
      },
      cpath: 'views/Demo.vue',
      component: 'Demo.vue'
    }
  ]

  res.status(200).send({
    code: 20000,
    msg: 'success',
    data: retStruct
  })
})

app.listen(9090, () => {
  console.log(`Server is running at 9090 ...`);
})

前端部分

import Vue from 'vue'
import VueRouter from 'vue-router'
import Home from '../views/Home.vue'
import axios from 'axios'

Vue.use(VueRouter)

const routes = [
  {
    path: '/',
    name: 'Home',
    component: Home
  },
  {
    path: '/about',
    name: 'About',
    // route level code-splitting
    // this generates a separate chunk (about.[hash].js) for this route
    // which is lazy-loaded when the route is visited.
    component: () => import(/* webpackChunkName: "about" */ '../views/About.vue')
  }
]

const router = new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
  // routes: [...routes, ...routeFromServer]
  routes
})

function _import (file, fileName) {
  // console.log(file)
  return () => import(/* webpackChunkName: "dynamic-route-" */ '@/' + file)
}

axios.get('http://localhost:9090/api')
  .then(res => res.data)
  .then(res => {
    res.data.forEach(v => {
      console.log(v)
      v.component = _import(v.cpath, v.name)
      router.addRoute('/', v)
    })

    // console.log(router.getRoutes())
  })
  .catch(err => {
    console.log(err)
  })

export default router

router.beforeEach((to, from, next) => {
  console.log(to, from)
  next()
})

已标记关键词 清除标记
相关推荐
©️2020 CSDN 皮肤主题: 成长之路 设计师:Amelia_0503 返回首页