vue-router是如何解析query参数呢?

62 阅读1分钟

案例:

?name=abc&age=123&name=def

<!-- 解析结果 -->
{
  name:['abc','def'],
  age:12
}

解析query的函数

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

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

  if (!query) {
    return res
  }
  // 遍历&符号连接的query参数
  query.split('&').forEach(param => {
    const parts = param.replace(/\+/g, ' ').split('=')
    const key = decode(parts.shift())
    const val = parts.length > 0 ? decode(parts.join('=')) : null
    // 1.没有相同key时,是一个string
    if (res[key] === undefined) {
      res[key] = val
    // 2.value是数组,将val追加到数组
    } else if (Array.isArray(res[key])) {
      res[key].push(val)
    // 3.以后相同的key,将val赋值为数组
    } else {
      res[key] = [res[key], val]
    }
  })

  return res
}

// 解码
export function decode (str: string) {
  try {
    return decodeURIComponent(str)
  } catch (err) {
    if (process.env.NODE_ENV !== 'production') {
      warn(false, `Error decoding "${str}". Leaving it intact.`)
    }
  }
  return str
}