1. 程式人生 > 其它 >vue實時獲取路由地址

vue實時獲取路由地址

文章目錄
方式一:window.location
方式二:vue-router
1.this.$route的內容:
(1)this.$route.fullPath:
(2)this.$route.hash
(3)this.$route.matched
(4)this.$route.meta、this.$route.name
(5)this.$route.name
(6)this.$route.params
(7)this.$route.query
2.實時獲取route地址並根據地址做處理

1. 方式一:window.location
測試網址:http://www.myurl.com:8866/test?id=123&username=xxx


1.window.location.href(當前URL)
結果:http://www.myurl.com:8866/test?id=123&username=xxx
2.window.location.protocol(協議)
結果:http
3.window.location.host(域名 + 埠)
結果:www.myurl.com:8866
4.window.location.hostname(域名)
結果:www.myurl.com
5.window.location.port(埠)
結果:8866
6.window.location.pathname(路徑部分)
結果:/test
7.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)

8.window.location.origin(’?'前邊的URL)
結果:http://www.myurl.com:8866
9.window.location.hash(獲取#之後的內容)
結果:null
2. 方式二:vue-router
1.this.$route的內容:

(1)this.$route.fullPath:
完成解析後的 URL,包含查詢引數和 hash 的完整路徑,即 “埠號/#” 之後的內容。

(2)this.$route.hash
當前路由的 hash 值 (帶 #) ,如果沒有 hash 值,則為空字串。

(3)this.$route.matched
官網說明:一個數組,包含當前路由的所有巢狀路徑片段的路由記錄 。路由記錄就是 routes 配置陣列中的物件副本 (還有在 children 陣列)。

(4)this.$route.meta、this.$route.name


(5)this.$route.name
當前路由的名稱,如果有的話。

(6)this.$route.params
一個 key/value 物件,包含了動態片段和全匹配片段,如果沒有路由引數,就是一個空物件。


(7)this.$route.query
一個 key/value 物件,表示 URL 查詢引數。如果沒有查詢引數,則是個空物件。


2.實時獲取route地址並根據地址做處理

watch: {
    $route(val) {
      //val即是this.$route
      //根據路由控制其他引數做不同處理
      if (val.path == "/xinyidai") {
        this.isCur = 5;
      } else if (val.path == "/fiProduct" || val.path == "/fiProductDetail") {
        this.isCur = 1;
      } else if (val.path == "/fiProductBx" ||val.path == "/fiProductBxDetail") {
        this.isCur = 2;
      } else if (val.path == "/stock" || val.path == "/stockDetail") {
        this.isCur = 4;
      } else {
        this.isCur = "";
      }
    },
  },

原文地址:https://blog.csdn.net/qq_42855675/article/details/113864784