vue刷新頁面后params參數(shù)丟失的原因和解決方法
頁面跳轉(zhuǎn)($router)方式
方式一(刷新頁面參數(shù)會丟失)
此方法不會在瀏覽器 url 地址欄中顯示傳遞的參數(shù)
this.$router.push({ name: 'a', params: { name: '張三', age: '18' }}) // 頁面跳轉(zhuǎn) this.$route.params // 參數(shù)接收
方式二(刷新頁面參數(shù)不會丟失)
此方法會在瀏覽器 url 地址欄中顯示傳遞的參數(shù)(數(shù)據(jù)會暴露在外面),即:'a?name=張三&age=18'
this.$router.push({ path: 'a', query: { name: '張三', age: '18' }}) // 頁面跳轉(zhuǎn) this.$route.query // 參數(shù)接收
刷新頁面后 params 參數(shù)丟失
發(fā)送數(shù)據(jù)的頁面A
this.$router.push({ name: 'A', params: { name: '張三', age: '18' }})
接收數(shù)據(jù)的頁面B
this.curObj = this.$route.params
當進入 B 頁面后,按 F5 刷新頁面 B 頁面接收的參數(shù)會丟失。
解決辦法
使用 localStorage 或 sessionStorage 瀏覽器自帶的 mini 數(shù)據(jù)庫(即本地存儲)
存儲在 localStorage 里的數(shù)據(jù)如果不是主動去清除的話,就算瀏覽器關(guān)閉了,下次打開瀏覽器數(shù)據(jù)還是會存在,是一個長期的存在。
存儲在 sessionStorage 里的數(shù)據(jù)只要關(guān)閉瀏覽器就會自動清除,但是刷新網(wǎng)頁不會清除,是一個臨時的存在。
可以利用 vue 里瀏覽器刷新不會觸發(fā) beforeDestory 生命周期函數(shù)和數(shù)據(jù)儲存本地這兩個方法來補全 params 刷新丟失數(shù)據(jù)的短板。
發(fā)送數(shù)據(jù)的頁面A
this.$router.push({ name: 'A', params: { name: '張三', age: '18' }})
接收數(shù)據(jù)的頁面B
mounted() { let routeParam = this.$route.params if (Object.entries(routeParam).length === 0) { routeParam = JSON.parse(sessionStorage.getItem('storageObj')) // 從本地存儲中獲取數(shù)據(jù) } else { sessionStorage.setItem('storageObj', JSON.stringify(routeParam)) // 將數(shù)據(jù)儲存在本地存儲里面 } this.curObj = routeParam }, beforeDestroy() { sessionStorage.removeItem('storageObj') // 將數(shù)據(jù)從本地存儲刪掉 },
沒有用 localStorage 是因為如果用戶跳轉(zhuǎn)到頁面 B 后,直接關(guān)閉瀏覽器,再打開瀏覽器輸入網(wǎng)址,就能從本地存儲找到該數(shù)據(jù),但 sessionStorage 關(guān)閉瀏覽器,數(shù)據(jù)就消失了。不會出現(xiàn) localStorage 的問題。
以上就是vue刷新頁面后params參數(shù)丟失的原因和解決方法的詳細內(nèi)容,更多關(guān)于vue刷新頁面后params丟失的資料請關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
Vue3?watchEffect的使用教程和相關(guān)概念
Vue?3?引入了?Composition?API,其中?watchEffect?是一個非常強大的工具,用于響應式地追蹤依賴項的變化,本文將詳細介紹?watchEffect?的使用方法和相關(guān)概念,文中有詳細的代碼供大家參考,需要的朋友可以參考下2024-08-08