一、原生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>
頁面效果:

二、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>
