有没有办法在Vue.js中输入route.params?

Nul*_*urt 10 vue.js vue-router

我在对vue.js 应用程序进行 Typescript 化时遇到了麻烦。我尝试从中提取一个参数route.params并将其分配给反应形式的属性。然而,TypeScript 给了我一个警告,参数的类型必须是string|string[],因此不能将其分配给string属性。我想出的唯一解决方案如下

form.productId = route.params.productId as string
Run Code Online (Sandbox Code Playgroud)

我认为如果我可以输入 的参数,这将是一个更好的解决方案route.params,但我不知道该怎么做。如果有人可以提供帮助,我将不胜感激。

And*_*hiu 9

这些route.params已经输入,这就是您看到警告的原因。

它们的类型是string | string[],因为一条路由可以多次拥有一个参数,该参数在内部会转换为字符串数组。

有几个正确的解决方案:

  1. 如果您知道此参数永远不会在 URL 中提供多次,并且始终在此特定路由上提供,则必须通过强制转换将此信息传递给 TypesScript
const productId = router.params.productId as string
// from here on `productId` is treated as string
Run Code Online (Sandbox Code Playgroud)
  1. 如果参数可以多次提供和/或可能丢失,请使用类型保护来处理每种情况:
const { productId } = router.params

if (typeof productId === "string") {
  // treat `productId` as string
} else if (Array.isArray(productId)) {
  // treat `productId` as string[]
} else {
  // treat `productId` as undefined
}
Run Code Online (Sandbox Code Playgroud)

  • 更好的是,你可以在 `if` 内自动执行 `if (typeof param1 === 'string') { // param1 will be string here } ` ;) (2认同)