您当前的位置:易学堂 > 日志记录

Vue如何获取url路由地址和参数简单示例

时间:2023-03-31 10:46:57

这篇文章主要给大家介绍了Vue如何获取url路由地址和参数的相关资料,通过简单的代码示例,帮助读者快速掌握Vue路由的基本用法,需要的朋友可以参考下!

1.window.location

实例:http://www.myurl.com:8866/test?id=123&username=xxx

当前URL

window.location.href
结果:http://www.myurl.com:8866/test?id=123&username=xxx

协议

window.location.protocol
结果:http

域名 + 端口

window.location.host
结果:www.myurl.com:8866

域名

window.location.hostname()
结果:www.myurl.com

端口

window.location.port()
结果:8866

路径部分

window.location.pathname()
结果:/test

请求的参数

window.location.search
结果:?id=123&username=xxx

备注:获取参数

// var url="www.baidu.com?a=1&b=2&C=3";//测试地址

/*
 * 分析:最前面是?或&,紧跟着除 ?&#以外的字符若干
 * 然后再等号,最后再跟着除 ?&#以外的字符
 * 并且要分组捕获到【除?&#以外的字符】
 */
 
var reg=/[?&]([^?&#]+)=([^?&#]+)/g;
var param={};
var ret =  reg.exec(url);
while(ret){ // 当ret为null时表示已经匹配到最后了,直接跳出
	param[ret[1]]=ret[2];
	ret = reg.exec(url);
}
console.log(param)

获取’?'前边的URL

window.location.origin()
结果:http://www.myurl.com:8866

获取#之后的内容

window.location.hash
结果:null

2.vue-router 获取参数

  • this.$route

  • this.$route.fullPath

  • this.$route.hash

  • this.$route.matched

  • this.$route.meta

  • this.$route.params

  • this.$route.query

补充:vue获取地址栏地址url截取参数

vue获取地址栏地址url截取参数 方法 (新建js文件)

export function UrlSearch(){<!--{cke_protected}{C}%3C!%2D%2D%20%2D%2D%3E-->
let name,value,str=location.href,num=str.indexOf("?"); //取得整个地址栏
str=str.substr(num+1); //取得所有参数 stringvar.substr(start [, length ]
let arr=str.split("&"); //各个参数放到数组里
console.log(arr)
for(let i=0;i < arr.length;i++){<!--{cke_protected}{C}%3C!%2D%2D%20%2D%2D%3E-->
num=arr[i].indexOf("=");
if(num>0){<!--{cke_protected}{C}%3C!%2D%2D%20%2D%2D%3E-->
name=arr[i].substring(0,num);
value=arr[i].substr(num+1);
this[name]=value;
}
}
}

在main.js引入

aa650abf698a82b8aacd2c43012c4cdc_202303310956056.png

挂载到全局

6e04d6aeea646152966554d922f3219c_202303310956057.png

使用

350ffad63f1e141fa379467a2012ffc6_202303310956068.png

标签: Vue