如何處理vue router 路由傳參刷新頁面參數(shù)丟失
常見場景:點(diǎn)擊列表的詳情,跳轉(zhuǎn)到詳情內(nèi)頁,在內(nèi)頁根據(jù)傳遞的參數(shù)獲取詳情數(shù)據(jù)。
路由傳參一般有如下幾種方式,下面主要介編程式導(dǎo)航 router.push 的傳參方式:
方法一:通過 params 傳參路由配置如下:
{ path: ’/detail/:id’, //若id后面加?代表這個參數(shù)是可選的 name: ’detail’, component: Detail }
通過 $router.push 中 path 攜帶參數(shù)的方式
// 列表中的傳參goDetail(row) { this.$router.push({path: `/detail/${row.id}` })}// 詳情頁獲取參數(shù)this.$route.params.id
通過 $router.push 的 params 傳參
// 列表頁傳參goDetail(row) { this.$router.push({name: ’detail’,params: { id: row.id} })}// 詳情頁獲取this.$route.params.id
注:這種方式的傳參,路徑用 name,路徑用 name,路徑用 name , 用 path 會獲取不到;如果在路由配置中沒有添加 /:id即 path: ’detail’,url 中不會顯示 id,在詳情頁還是可以拿到參數(shù) id,但刷新后參數(shù)丟失。
以上這兩種方式,傳遞的參數(shù) id 會在 url 后面顯示,如圖:
傳遞的參數(shù)會暴露在網(wǎng)址中。
如果在路由中設(shè)置了params參數(shù) /:id,但是在跳轉(zhuǎn)的時候沒有傳遞參數(shù),會導(dǎo)致頁面沒有內(nèi)容或跳轉(zhuǎn)失敗,可在后面加 ?代表這個參數(shù)是可選的,即 /:id?
方法二:通過 query 傳參// 路由配置{ path: ’/detail’, name: ’detail’, component: Detail }// 列表頁goDetail(row) { this.$router.push({path: ’/detail’,query: { id: row.id} })}// 詳情頁this.$route.query.id
注:這種方式傳遞的參數(shù)會在地址欄的 url 后面顯示 ?id=?,類似于 get 傳參;query 必須配合 path 來傳參。
傳遞的參數(shù)是對象或數(shù)組
還有一種情況就是,如果通過 query 的方式傳遞對象或數(shù)組,在地址欄中會被強(qiáng)制轉(zhuǎn)換成 [object Object],刷新后也獲取不到對象值。
此時可以通過 JSON.stringify() 方法將要傳遞的參數(shù)轉(zhuǎn)換為字符串傳遞,在詳情頁再通過 JSON.parse() 轉(zhuǎn)換成對象。
let parObj = JSON.stringify(obj)this.$router.push({ path: ’/detail’, query: {’obj’: parObj }})// 詳情頁JSON.parse(this.$route.query.obj)
這個方法雖然可以傳遞對象,若數(shù)據(jù)少還好,數(shù)據(jù)多的話地址欄就很長了
注意:在所有的子組件中獲取路由參數(shù)是 $route不是 $router
以上 params 和 query 傳參方式對比:
通過 $router.push 的 params + name 傳參,若路由中沒有設(shè)置params參數(shù),參數(shù)不會拼接在路由后面,但是頁面刷新參數(shù)會丟失。 通過 $router.push 中 path 攜帶參數(shù)或通過 query 傳參,參數(shù)會拼接在地址后面,會暴露信息。方法三:使用 props 配合組件路由解耦// 路由配置{ path: ’/detail/:id’, name: ’detail’, component: Detail, props: true // 如果props設(shè)置為true,$route.params將被設(shè)置為組件屬性}// 列表頁goDetail(row) { this.$router.push({path: ’/detail’,query: { id: row.id} })}// 詳情頁export default { props: {// 將路由中傳遞的參數(shù)id解耦到組件的props屬性上id: String }, mounted: {console.log(this.id) }}
此外,還可以通過把參數(shù)存在 sessionStorage 或 localStorage 中來解決頁面刷新參數(shù)丟失的問題,具體結(jié)合實(shí)際項目即可。
以上就是如何處理vue router 路由傳參刷新頁面參數(shù)丟失的詳細(xì)內(nèi)容,更多關(guān)于vue的資料請關(guān)注好吧啦網(wǎng)其它相關(guān)文章!
相關(guān)文章:
1. asp(vbscript)中自定義函數(shù)的默認(rèn)參數(shù)實(shí)現(xiàn)代碼2. Ajax實(shí)現(xiàn)表格中信息不刷新頁面進(jìn)行更新數(shù)據(jù)3. jsp EL表達(dá)式詳解4. jsp中sitemesh修改tagRule技術(shù)分享5. JavaWeb Servlet中url-pattern的使用6. 爬取今日頭條Ajax請求7. 如何使用瀏覽器擴(kuò)展篡改網(wǎng)頁中的JS 文件8. ASP基礎(chǔ)知識VBScript基本元素講解9. ASP刪除img標(biāo)簽的style屬性只保留src的正則函數(shù)10. JSP servlet實(shí)現(xiàn)文件上傳下載和刪除
