最近想用vue3撸个基础后台方便后边接单啥的

用到了一个小技术 通过api动态加载路由,刚开始写的时候老是报错

vue Invalid route component
找了好多文档都没找道原因,后边看到某篇博客使用 $拼接参数,就试了一下 没想到可以了

现在复盘一下

我的原始操作

api请求的json 也是就模拟了一个api返回路由

xxx.json

[
  {
    "path": "/About",
    "name": "About",
    "component": "../views/About"
  }
]

router.js

import {createRouter, createWebHashHistory} from 'vue-router'
import NotFound from   "../views/NotFound.vue"
const routes = [
    {
        name: "Home",
        path: "/",
        component: () => import('../views/Home')
    },
//匹配所有没有匹配到的
    { path: '/:pathMatch(.*)*', name: 'NotFound', component: NotFound },
]

const router = createRouter({
    history: createWebHashHistory(),
    routes
})

在最后 添加这么两行

假装是请求回来的

import jj from "/public/tsconfig.json"
//添加到路由里
 jj.forEach((item) => {
     console.log(item)
     router.addRoute({
         path: item.path,
         name: item.name,
         component: () => import(item.component)
     })
 })

这个时候启动vue就报错了

vue Invalid route component
后边就修改模拟数据

[
  {
    "path": "/About",
    "name": "About",
    "component": "views/About"
  }
]

添加路由改成了

import jj from "/public/tsconfig.json"
jj.forEach((item) => {
    console.log(item.component)
    router.addRoute({

        path: item.path,
        component: () => import(`@/${item.component}`)
    })
})

这个时候就访问正常了
就是这一句

import(`@/${item.component}`)

源码 可以到这里下载 下载

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐