From a50180f6538aba51074f0152157075337e73a4fd Mon Sep 17 00:00:00 2001 From: MaYuanhai <414199639@qq.com> Date: Thu, 11 Jun 2020 20:18:23 +0800 Subject: [PATCH] fix[utils]: param2Obj bug when url params includes ==(#3100) --- src/utils/index.js | 28 +++++++++++++++------------- tests/unit/utils/param2Obj.spec.js | 14 ++++++++++++++ 2 files changed, 29 insertions(+), 13 deletions(-) create mode 100644 tests/unit/utils/param2Obj.spec.js diff --git a/src/utils/index.js b/src/utils/index.js index 96ee6e7f..50da2621 100644 --- a/src/utils/index.js +++ b/src/utils/index.js @@ -162,19 +162,21 @@ export function param(json) { * @returns {Object} */ export function param2Obj(url) { - const search = url.split('?')[1] - if (!search) { - return {} - } - return JSON.parse( - '{"' + - decodeURIComponent(search) - .replace(/"/g, '\\"') - .replace(/&/g, '","') - .replace(/=/g, '":"') - .replace(/\+/g, ' ') + - '"}' - ) + const search = decodeURIComponent(url.split('?')[1]).replace(/\+/g, ' ') + if (!search) { + return {} + } + const obj = {} + const searchArr = search.split('&') + searchArr.forEach(v => { + const index = v.indexOf('=') + if (index !== -1) { + const name = v.substring(0, index) + const val = v.substring(index + 1, v.length) + obj[name] = val + } + }) + return obj } /** diff --git a/tests/unit/utils/param2Obj.spec.js b/tests/unit/utils/param2Obj.spec.js new file mode 100644 index 00000000..e106ed88 --- /dev/null +++ b/tests/unit/utils/param2Obj.spec.js @@ -0,0 +1,14 @@ +import { param2Obj } from '@/utils/index.js' +describe('Utils:param2Obj', () => { + const url = 'https://github.com/PanJiaChen/vue-element-admin?name=bill&age=29&sex=1&field=dGVzdA==&key=%E6%B5%8B%E8%AF%95' + + it('param2Obj test', () => { + expect(param2Obj(url)).toEqual({ + name: 'bill', + age: '29', + sex: '1', + field: window.btoa('test'), + key: '测试' + }) + }) +})