Vue路由传中文或特殊字符乱码的本质是URL编码不一致,应使用encodeURIComponent/decodeURIComponent处理query参数,params路径参数需先encodeURIComponent再btoa编码,接收时反向解码。

Vue 路由传中文或特殊字符时出现乱码,本质是 URL 编码没做对。直接拼接未编码的字符串进 query 或 params,浏览器会自动用默认方式处理,但解码逻辑不匹配就出问题。关键不是“要不要编码”,而是“用什么方式编、在哪一步解”。
用 encodeURIComponent + decodeURIComponent 处理 query 参数
这是最常用也最稳妥的方式,适用于 GET 类型的路由传参(即 URL 中 ? 后的部分)。
- 跳转时编码:在
this.$router.push或router.push中,对每个 query 值显式调用encodeURIComponent - 接收时解码:在目标组件中,用
decodeURIComponent还原,不能依赖框架自动处理 - 注意不要对整个 URL 字符串用
encodeURIComponent,只处理参数值本身
示例:
跳转端
立即学习“前端免费学习笔记(深入)”;
this.$router.push({ path: '/search', query: { keyword: encodeURIComponent('上海地铁') } })
接收端
const keyword = decodeURIComponent(this.$route.query.keyword || '')
含中文的 params 路径参数需配合 encodeURI 或 Base64
如果使用命名路由 + params(如 /user/:name),且 name 是中文,单纯靠 encodeURI 不够稳定——部分浏览器对路径中编码的支持不一致,容易 404 或解析失败。
- 推荐方案:先
encodeURIComponent,再用btoa做 Base64 编码(因为btoa不支持 Unicode,必须先 UTF-8 编码) - 接收时按顺序反向操作:
atob→decodeURIComponent - 也可封装成工具函数,避免每次重复写逻辑
示例编码流程:
const encoded = btoa(encodeURIComponent('张三')) // 得到 '5byg5LiJ'
this.$router.push({ name: 'userDetail', params: { id: encoded } })
接收时:
const raw = atob(this.$route.params.id); const name = decodeURIComponent(raw);
避免踩坑的几个细节
很多问题其实不是编码本身,而是混用了不同层级的编码函数或遗漏了解码步骤。
-
encodeURI和encodeURIComponent作用范围不同:前者适合整个 URL,后者专用于单个参数值;传参一律用后者 -
URLSearchParams自动处理键值编码,但只适用于 query,不适用于 params 或 hash - 服务端返回的链接如果已含编码,前端不要再套一层,否则会双重编码(如 %E9%BB%84 → %25E9%25BB%2584)
- Vue Router 4(Vue 3)中,
router.push的query对象值不会被自动编码,必须手动处理
简化开发:封装一个参数编解码工具
把常用逻辑收口,减少出错概率。例如在 utils/router.js 中:
export const encodeParam = (str) => btoa(encodeURIComponent(str));
export const decodeParam = (str) => decodeURIComponent(atob(str));
使用时直接调用,语义清晰,团队协作也更容易对齐规范。



















