window.location.href
或者location.href
或者window.location
获得地址栏中的所有内容,decodeURI()
可以解码地址栏中的数据 恢复中文数据,window.location.search
获得地址栏中问号及问号之后的数据
# 一、字符串拆分
GetLocation(value) {
var url = decodeURI(`?id="123456"&Name="蒜薹炒肉"`); // location.search
var object = {};
if (url.indexOf("?") != -1) // url中存在问号,也就说有参数。
{
var str = url.substr(1); // 得到?后面的字符串
var strs = str.split("&"); // 将得到的参数分隔成数组[id="123456",Name="蒜薹炒肉"];
for (var i = 0; i < strs.length; i++) {
object[strs[i].split("=")[0]] = strs[i].split("=")[1]
}
}
return object[value];
},
console.log(GetLocation('id')) // "123456"
1
2
3
4
5
6
7
8
9
10
11
12
13
14
2
3
4
5
6
7
8
9
10
11
12
13
14
# 二、正则匹配法
function GetLocation(name) {
var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
var r = window.location.search.substr(1).match(reg);
if (r != null) {
return unescape(r[2]);
}
return null;
}
console.log(GetLocation('')) // 以 & 来查找参数
1
2
3
4
5
6
7
8
9
2
3
4
5
6
7
8
9
# 三、vue中更简单点
this.$route.path 当前页面路由
this.$route.params 路由参数
this.$route.query 查询路由参数
1
2
3
2
3