UniApp 中处理路由传参时的中文乱码问题

在 UniApp 中处理路由传参时的中文乱码问题,主要是因为 URL 对特殊字符(包括中文)需要进行编码和解码处理。以下是详细解决方案:

1. 传递参数时进行编码

使用 encodeURIComponent() 对包含中文的参数进行编码:


// 在跳转页面时

uni.navigateTo({
  url: `/pages/detail/detail?name=${encodeURIComponent('张三')}&age=20`
});

2. 接收参数时进行解码

在目标页面的 onLoad 生命周期中,使用 decodeURIComponent() 解码:


// 在目标页面的 onLoad 中

onLoad(options) {
  // 解码中文参数
  this.name = decodeURIComponent(options.name);
  this.age = options.age; // 非中文参数无需解码
}