vue獲取瀏覽器地址欄參數(?及/)路由+非路由實現方式


1、? 參數

瀏覽器參數形式:http://javam4.com/m4detail?id=1322914793170014208

1.1、路由取參方式
this.$route.query.id

前端跳轉方式:

一、onclick方式
<a 
   title="測試數據"
   @click="test(row.id)"
   target="_blank">
   <span>{{ row.title }}</span>
</a>

test(id) {
    this.$router.push({
        path: "/m4detail",
        query: {
            id: id
        }
    });
}

二、a標簽直接跳轉
<a 
   title="測試數據"
   :href="javam4.com/m4detail/' + row.id"
   target="_blank">
   <span>{{ row.title }}</span>
</a>

簡單粗暴,只要你的瀏覽器地址欄參數帶 ?號,不管你是咋跳轉過來的, this.$route.query 后面直接 . 對應的參數就可以取到值,比如 ?id=1323968&name=1111

對應效果如下:

1.2、js取參方式

mothod 方法添加如下方法:

getUrlKey: function (name) {
    return decodeURIComponent((new RegExp('[?|&]' + name + '=' + '([^&;]+?)(&|#|;|$)').exec(location.href) || [, ""])[1].replace(/\+/g, '%20')) || null
}

調用直接通過 getUrlKey(參數名稱),具體如下:

2、/ 參數

瀏覽器參數形式:http://javam4.com/m4detail/1322914793170014208

2.1、路由方式

路由參數配置如下:

{ path: 'm4detail/:id', title: 'java面試網', name: 'm4detail', component: () => import('@/views/javam4/m4detail.vue') },

也就是由以前的 path: 'm4detail' > path: 'm4detail/:id'

這種方式需要 <router-link> 標簽配合使用:

<router-link :to="路徑"></router-link>

而界面跳轉的時候因為通常是一個 <a> 標簽,所以就可以不用了,直接套一層:

<router-link :to="`/m4detail/`+row.id" target="_blank">
    <a>
        <span>{{row.title}}</span>
    </a>
</router-link>

參數說明:

  • to:跳轉路徑,對應路由的 path
  • target:跳轉方式,跟a標簽用法一樣

界面取參:

this.$route.params.id

效果如下:

2.2、非路由方式

mothod 方法添加如下方法:

getUrlKey: function (directory) {
    return decodeURIComponent((new RegExp('/' + directory + '.*/([^/]+)/?$').exec(location.href) || [, ""])[1].replace(/\+/g, '%20')) || null
}

其中 directory 表示那個目錄后面的參數,比如:javam4.com/m4detail/11111111111

那么在這取值就是 m4detail,其實使用這種方式,無非還是用正則表達式切割一下,如果覺得正則不滿足大家也可以自行修改。

let id = this.getUrlKey("m4detail");
console.log("this.id:"+id);

代碼截圖:

效果截圖:

希望這篇文章對你有所幫助。

博客園:https://www.cnblogs.com/niceyoo


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM