7

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

 1 year ago
source link: http://xuedingmiao.com/blog/vue_router_plus_missing.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

遇到 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, '+')
}

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK