vue-router.esm-bundler.js?6c02:1474 Uncaught TypeError: Cannot read property ‘forEach‘ of undefined

关于vue-cli4.5.13中使用vue-router报错的问题。

以下是报错详情:

vue-router.esm-bundler.js?6c02:1474 Uncaught TypeError: Cannot read property 'forEach' of undefined
    at createRouterMatcher (vue-router.esm-bundler.js?6c02:1474)
    at new createRouter (vue-router.esm-bundler.js?6c02:2777)
    at eval (index.js?a18c:41)
    at Module../src/router/index.js (app.js:1482)
    at __webpack_require__ (app.js:854)
    at fn (app.js:151)
    at eval (main.js:12)
    at Module../src/main.js (app.js:1470)
    at __webpack_require__ (app.js:854)
    at fn (app.js:151)

先附上自己的router/index.js代码:

import { createRouter, createWebHistory } from 'vue-router'

const Home = ()=>import('views/home/Home')
const Category = ()=>import('views/category/Category')
const Cart = ()=>import('views/cart/Cart')
const Profile = ()=>import('views/profile/Profile')

const routers = [
  {
    path:'',
    redirect:'/home'
  },
  {
    path:'/home',
    component:Home
  },
  {
    path:'/category',
    component:Category
  },
  {
    path:'/cart',
    component:Cart
  },
  {
    path:'/profile',
    component:Profile
  }
]
const router = new createRouter({
  history:createWebHistory(),
  routers
})

export default router

百度了好多,发现都无济于事。于是自己寻找了半天发现在定义route数组的时候,把routes写成了routers。又因为在createRouter函数里面使用了简易写法,所以导致在参数里面找不到routes导致的报错。

下面附正确代码:

import { createRouter, createWebHistory } from 'vue-router'

// 懒加载
const Home = ()=>import('views/home/Home')
const Category = ()=>import('views/category/Category')
const Cart = ()=>import('views/cart/Cart')
const Profile = ()=>import('views/profile/Profile')

// 2.创建router
const routes = [
  {
    path:'',
    redirect:'/home'
  },
  {
    path:'/home',
    component:Home
  },
  {
    path:'/category',
    component:Category
  },
  {
    path:'/cart',
    component:Cart
  },
  {
    path:'/profile',
    component:Profile
  }
]

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

export default router

希望以后不要犯这种低级错误了

  • 7
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 4
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值