0
点赞
收藏
分享

微信扫一扫

vue-router接收带+号参数时加号丢失问题

遇到 vue 项目从 url 接收带+号的参数,参数中的加号丢失的处理方法

现象

从另一个项目跳过来,参数开头含有一个+号,但是请求接口时发现参数开头的+号丢了,导致报错。

原因

vue-router 的源码中对参数中的+号进行了处理,替换为了空格:
文件 ​​node_modules/vue-router/src/util/query.js​​:

function parseQuery (query: string): Dictionary<string> {
const res = {}

query = query.trim().replace(/^(\?|#|&)/, '')

if (!query) {
return res
}

query.split('&').forEach(param => {
const parts = param.replace(/\+/g, ' ').split('=')
const key = decode(parts.shift())
const val = parts.length > 0 ? decode(parts.join('=')) : null

if (res[key] === undefined) {
res[key] = val
} else if (Array.isArray(res[key])) {
res[key].push(val)
} else {
res[key] = [res[key], val]
}
})

return res
}

处理办法

在路由的拦截跳转函数 ​​beforeEach​​ 中增加处理,把空格替换回+号:

if(to.query.id) {
to.query.id = to.query.id.replace(/\s/g, '+')
}
举报

相关推荐

0 条评论