谈一谈vue-router4类型校验RouteRecordRaw

8,859 阅读1分钟

在这些类型中,"slice(...)" 返回的类型不兼容。不能将类型“RouteRecordRaw[]”分配给类型

项目:vue3 + ts 写的

截屏2022-04-29下午3.50.07.png

把鼠标移到红色波浪线上,发现里面提示写着:

类型"RouteRecordRaw[]"的参数不能赋值给类型 “ConcatArray。。。”的参数。

关于router.ts当中的RouteRecordRaw类型校验,是为了规划化ts开发,增加路由对象类型限制,好处就是允许在基础路由里面增加开发者自定义属性。

当用户通过routes option 或者 router.addRoute() 来添加路由时,可以得到路由记录。

  • path
  • redirect
  • children
  • alias
  • name
  • beforeEnter
  • props
  • meta

就是用ts定义route的类型时, 直接

import { RouteRecordRaw } from 'vue-router'

export const constantRoutes: RouteRecordRaw[] = [
    {
    path: '/',
    name: 'dashboard',
    redirect: '/dashboard',
    component: Layout,
    children: [
      {
        path: 'dashboard',
        component: () => import('@/views/dashboard/index.vue'),
        name: 'Dashboard',
        meta: {
          title: '首页',
          icon: 'dashboard'
        }
      }
    ]
  },
]

类型声明成: RouteRecordRaw[]

就不会报错了。