js获取url参数值的几种方式

时间:2021-04-12 16:22:57

一、原生js获取URL参数值:

  比如当前URL为:http://localhost:8080/#/page2?id=100&name=guanxy

<template>
<div>
<div>
<button style="background-color: orange" @click="getUrlParam">方式一:采用正则表达式获取地址栏参数 (代码简洁,重点正则)</button>
<p>结果:id={{method1_id}},name={{method1_name}}</p>
</div>
<div>
<button style="background-color: green" @click="getUrlParam2"> 方法二:split拆分法 (代码较复杂,较易理解)</button>
<p>结果:id={{method2_id}},name={{method2_name}}</p>
</div>
<div>
<button style="background-color: aqua" @click="getUrlParam3"> 方法三:split拆分法(根据参数名获取对应的值)</button>
<p>结果:id={{method3_id}},name={{method3_name}}</p>
</div>
</div>
</template> <script>
export default {
name: "page2",
data() {
return {
method1_id: '',
method1_name: '',
method2_id: '',
method2_name: '',
method3_id: '',
method3_name: '',
}
},
methods: {
getUrlParam() {
//为什么window.location.search取值为空?
//“http://localhost:8080/#/page2?id=100&name=guanxy”那么使用window.location.search得到的就是空(“”)。
// 因为“?id=100&name=guanxy”串字符是属于“#/page2?id=100&name=guanxy”这个串字符的,也就是说查询字符串search只能在取到“?”后面和“#”之前的内容,如果“#”之前没有“?”search取值为空。
this.method1_id = this.getQueryString('id');
this.method1_name = this.getQueryString('name');
},
getQueryString(name) {
let reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
let url = window.location.hash.split('?')[1].match(reg);
// console.log(url)
if (url != null) {
return decodeURI(url[2])//decodeURI() 函数可对 encodeURI() 函数编码过的 URI 进行解码。
} else {
return null
}
},
getUrlParam2() {
let url = window.location.hash.split('?')[1].split("&");
// console.log(url)
let paramObj = new Object()
url.forEach((item, i) => {
paramObj[item.split('=')[0]] = item.split('=')[1]
})
this.method2_id = paramObj.id,
this.method2_name = paramObj.name
},
getUrlParam3() {
this.method3_id = this.getQueryVariable('id');
this.method3_name = this.getQueryVariable('name')
},
getQueryVariable(variable) {
let url = window.location.hash.split('?')[1].split("&");
for (let i = 0; i < url.length; i++) {
let pair = url[i].split('=');
if (pair[0] == variable) {
return pair[1]
}
}
return false
}
}
}
</script> <style scoped> </style>

页面效果:

js获取url参数值的几种方式

二、Vue 获取URL参数值

  <p>params获取当前路由参数:id={{this.$route.params.id}},name={{this.$route.params.name}}</p>
<p>query获取当前路由参数:id={{this.$route.query.id}},name={{this.$route.query.name}}</p>