Vue Router 中 params 传递 null 值转为字符串问题分析

340 阅读1分钟

在使用 Vue Router 进行路由跳转时,如果传递到 params 中的值是 null,在目标页面中接收时,该值会被转为字符串 "null"。这是为什么?

问题重现

为了实现路由跳转,我使用 Vue Router 传递一个 params 值为 null

this.$router.push({
  name: 'user',
  params: { id: null }
});

目标路由的配置如下:

{
  path: '/user/:id',
  name: 'user',
  component: UserPage
}

跳转后,路由 URL 为:

/user/null

在目标页面中接收到:

console.log(this.$route.params.id); // 输出 "null" (字符串)

展现为值为 null 的参数,已被转为字符串 "null"

原因分析

1. Vue Router 设计原理

在 Vue Router 中,传递到 params 中的值会被用于构建 URL 路径。由于路径应该仅仅包含字符串,所有非字符串的值会被字符串化。

params 中包含 null,它会被字符串化为 "null",进入 URL 路径中。同样,如果值是 undefined,则该参数会被忽略。

2. URL 解析和页面接收

在目标页面中,接收到的 params 是 Vue Router 通过分析 URL 并转换得到的值。由于 URL 中已包含字符串 "null",因此在目标页面中显示为字符串而不是原始的 null

解决方案

方案 1:使用 query 代替 params

如果想保留原始值的数据类型,可以选择使用 query,而不是 params

this.$router.push({
  name: 'user',
  query: { id: null }
});

// 目标页面中接收
console.log(this.$route.query.id); // 输出 null

query 参数会保留原始值而不进行字符串化。

方案 2:跳转前处理 null

在跳转前,将 null 转换为其他值,如空字符串或者 undefined,然后在目标页面进行解析。

this.$router.push({
  name: 'user',
  params: { id: null ?? 'default' }
});

目标页面中:

const id = this.$route.params.id === 'default' ? null : this.$route.params.id;

方案 3:目标页面解析 "null"

如果想保持 params,可以在目标页面中手动解析。

const id = this.$route.params.id === 'null' ? null : this.$route.params.id;

这样,如果值为 "null",则转换为 null

总结

将值传递到 Vue Router 的 params,如果包含 null,转换为字符串是由于字符串化规则出发的。为了避免该问题,可以选择使用 query 代替,或在跳转前或接收时进行选择性处理。