无法找到我应该用于路由链接的 TS 接口。
我的 Vue 3 + Typescript 应用程序中有一个共享组件,它接收内部和外部链接。将它们视为祝酒消息。
HTML 看起来像这样:
// v-for toast in toasts
{{ toast.message }}
<button
class="my-button-class"
tag="a"
:to="toast.external_url">
{{ toast.call_to_action }}
</button>
这就是这些 toast 的 Typescript 定义。你可以传入
internal_url
或external_url
:
import type { RouteRecord } from 'vue-router';
export interface Toast {
message: string;
call_to_action: string;
external_url?: string;
interal_url?: RouteRecord; // RouteLocation, etc. doesn't work
}
我的问题是我找不到需要用于
internal_url
的确切 TS 定义。
Vue Router 文档
中的
RouteRecord
、RouteLocation
等不起作用。 Toast 消息的典型用法如下所示:
addToast({
message: 'Someone viewed your profile',
call_to_action: 'Review',
internal_url: { name: routeNames.profile, query: { id: current_user.id }}
}
我认为 RouteLocation 是完美的界面,但它也不正确。
来自
RouteLocation
的错误示例:
Type internal_url is missing the following properties from type 'RouteLocation': matched, fullPath, hash, redirectedFrom, and 3 more.
当您想使用名称导航到路线并可能传递查询参数时,您确实应该使用注释中提到的
RouteLocationRaw
接口。然而,您似乎正在将 Vue Router 与 TypeScript 结合使用,有时类型推断可能有点棘手。
更新 Toast 界面以正确定义
internal_url
属性:
export interface Toast {
message: string;
call_to_action: string;
external_url?: string;
internal_url?: RouteLocationRaw;
}
现在您可以在代码中将
internal_url
属性与 RouteLocationRaw 类型一起使用:
import { RouteLocationRaw } from 'vue-router';
// Define your route names
const routeNames = {
profile: 'profile', // replace this with your actual route name
};
// Example usage
addToast({
message: 'Someone viewed your profile',
call_to_action: 'Review',
internal_url: { name: routeNames.profile, query: { id: current_user.id }}
});