方法一:
getRequest(url) {
const res = {}
if (url.includes('?')) {
const str = url.split('?')[1]
const arr = str.split('&')
arr.forEach(item => {
const key = item.split('=')[0]
const val = item.split('=')[1]
res[key] = decodeURIComponent(val) // 解码
})
}
return res
},
// url :http://192.168.11.101:8082/#/pages/gate/qrc?channelId=12&id=3
console.log(this.getRequest(window.location.href))
// {
// channerlId:'12',
// id:'3'
// }
方法二:
// 创建一个URLSearchParams实例
const urlSearchParams = new URLSearchParams(window.location.search);
// 把键值对列表转换为一个对象
const params = Object.fromEntries(urlSearchParams.entries());
console.log(params) // { user: '阿飞', age: '16' }
window.location常用方法介绍
1,window.location.href
整个URl字符串(在浏览器中就是完整的地址栏)
本例返回值 http://192.168.11.101:8082/#/pages/gate/qrc?channelId=12&id=3
2,window.location.protocol
URL 的协议部分
本例返回值:http:
3,window.location.host
URL 的主机部分
本例返回值:192.168.11.101:8082
4,window.location.port
URL 的端口部分
如果采用默认的80端口(update:即使添加了:80),那么返回值并不是默认的80而是空字符
本例返回值:8082
5,window.location.pathname
URL 的路径部分(就是文件地址)
本例返回值:/
6,window.location.search
查询(参数)部分
除了给动态语言赋值以外,我们同样可以给静态页面,并使用javascript来获得相信应的参数值
本例返回值:?channelId=12&id=3
7,window.location.hash
锚点