Vue-Router4/TypeScript“没有重载匹配这个调用”
Posted
技术标签:
【中文标题】Vue-Router4/TypeScript“没有重载匹配这个调用”【英文标题】:Vue-Router4/TypeScript "No overload matches this call" 【发布时间】:2021-10-12 06:31:31 【问题描述】:我正在尝试使用 typescript 将多个 vue-router 4 file.ts 连接到主 vue-router(index.ts),但它给出了错误“TS2769:没有重载匹配此调用. 重载 1 of 2,'(...items: ConcatArray[]): never[]',给出了以下错误。 “RouteRecordRaw[]”类型的参数不可分配给“ConcatArray”类型的参数。 'slice(...)' 返回的类型在这些类型之间不兼容。 类型 'RouteRecordRaw[]' 不可分配给类型 'never[]'...."
这是我的文件。
DashboardRouter.ts
import RouteRecordRaw from "vue-router";
const DashboardRouter: Array<RouteRecordRaw> = [
path: "/",
redirect: "/dashboard",
component: () => import("@/layout/Layout.vue"),
children: [
path: "/dashboard",
name: "dashboard",
component: () => import("@/views/Dashboard.vue"),
,
]
,
];
export default DashboardRouter;
GuestRouter.ts
import RouteRecordRaw from "vue-router";
const GuestRouter: Array<RouteRecordRaw> = [
path: "/login",
name: "login",
component: () => import("@/views/auth/Login.vue")
,
path: "/password-reset",
name: "password-reset",
component: () => import("@/views/auth/PasswordReset.vue")
,
// the 404 route, when none of the above matches
path: "/404",
name: "error-404",
component: () => import("@/views/error/Error404.vue")
,
path: "/:pathMatch(.*)*",
redirect: "/404"
];
export default GuestRouter;
Index.ts(主路由器)
import createRouter, createWebHistory, RouteRecordRaw from "vue-router";
import store from "@/store";
import Mutations, Actions from "@/store/enums/StoreEnums";
import DashboardRoute from "./DashboardRouter";
import GuestRoute from "./GuestRouter";
const routes: Array<RouteRecordRaw> = [].concat(GuestRoute, DashboardRoute);
const router = createRouter(
history: createWebHistory(),
routes
);
router.beforeEach(() =>
// reset config to initial state
store.commit(Mutations.RESET_LAYOUT_CONFIG);
// Scroll page to top on every route change
setTimeout(() =>
window.scrollTo(0, 0);
, 100);
);
export default router;
【问题讨论】:
【参考方案1】:问题是[]
没有输入。
解决此问题的一种方法是在[]
上使用type assertion:
const routes: Array<RouteRecordRaw> = ([] as Array<RouteRecordRaw>).concat(GuestRoute, DashboardRoute);
// or
const routes = ([] as Array<RouteRecordRaw>).concat(GuestRoute, DashboardRoute);
// or
const routes = ([] as RouteRecordRaw[]).concat(GuestRoute, DashboardRoute);
更简洁的方式是spread the arrays:
const routes: Array<RouteRecordRaw> = [...GuestRoute, ...DashboardRoute];
// or
const routes: RouteRecordRaw[] = [...GuestRoute, ...DashboardRoute];
【讨论】:
【参考方案2】:你需要把RouteRecordRaw拆分出来,作为一个类型导入,就是这样:
import createWebHistory, createRouter from "vue-router";
import type RouteRecordRaw from "vue-router";
我遇到了同样的问题,几分钟前刚刚解决了。
【讨论】:
以上是关于Vue-Router4/TypeScript“没有重载匹配这个调用”的主要内容,如果未能解决你的问题,请参考以下文章
是否可以在 vue 2 中使用没有组件的 vue-router?
有没有办法使用 Vue-Router 从动态 URL 中删除目录?
如何在没有 vue-router 的情况下链接到静态 html 文件?
javascript 在URL #vuejs中使用没有哈希的Vue-router