如何處理vue router 路由傳參刷新頁面參數(shù)丟失
常見場景:點(diǎn)擊列表的詳情,跳轉(zhuǎn)到詳情內(nèi)頁,在內(nèi)頁根據(jù)傳遞的參數(shù)獲取詳情數(shù)據(jù)。
路由傳參一般有如下幾種方式,下面主要介編程式導(dǎo)航 router.push 的傳參方式:
方法一:通過 params 傳參路由配置如下:
{ path: ’/detail/:id’, //若id后面加?代表這個(gè)參數(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í)候沒有傳遞參數(shù),會導(dǎo)致頁面沒有內(nèi)容或跳轉(zhuǎn)失敗,可在后面加 ?代表這個(gè)參數(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],刷新后也獲取不到對象值。
此時(shí)可以通過 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)
這個(gè)方法雖然可以傳遞對象,若數(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í)際項(xiàng)目即可。
以上就是如何處理vue router 路由傳參刷新頁面參數(shù)丟失的詳細(xì)內(nèi)容,更多關(guān)于vue的資料請關(guān)注好吧啦網(wǎng)其它相關(guān)文章!
相關(guān)文章:
1. ASP中if語句、select 、while循環(huán)的使用方法2. 詳解瀏覽器的緩存機(jī)制3. ASP新手必備的基礎(chǔ)知識4. 利用FastReport傳遞圖片參數(shù)在報(bào)表上展示簽名信息的實(shí)現(xiàn)方法5. 推薦一個(gè)好看Table表格的css樣式代碼詳解6. phpstudy apache開啟ssi使用詳解7. HTML中的XML數(shù)據(jù)島記錄編輯與添加8. ASP常用日期格式化函數(shù) FormatDate()9. ASP.NET Core按用戶等級授權(quán)的方法10. .NET 中配置從xml轉(zhuǎn)向json方法示例詳解
