前言
本文主要介紹的是Vue利用History記錄上一頁面數據的相關內容,vue使用history后,能夠使得url更加漂亮,也就是不再有‘#'的問題,下面話不多說了,來一起看看詳細的介紹吧
UI


需求
從列表頁的第二頁進入詳情頁,返回時列表頁仍然顯示在第二頁;
從列表頁的第二頁進入詳情頁,返回時列表頁的篩選條件仍然存在。
<!--more-->
技術選擇
this.$router.push({path: path, query: query});方式,將頁碼和選擇條件作為參數存儲在url中,這種方式在上面的UI設計中是可行的,但是當列表頁中包含tab組件時(分頁組件是公用的),會因為push的因素(因為push會打開新頁面)導致一些問題(PS:也可能是本人技術能力的原因),未實現。location.hash方式獲取頁碼;通過history.state方式獲取存儲的選擇條件。具體實現--技術選擇2
開關
為分頁組件添加一個開關(openroute),因為需要灰度上線,萬一有問題,要調整的頁面也只有一個。代碼如下:
<script>
export default {
props: {
openroute: {
type: Boolean,
default: () => (true)
}
},
}
</script>
分頁組件中存儲頁碼和選擇條件&獲取頁碼
<script>
export default {
methods: {
fetchData(page) {
//請求參數
let params = this.params;
//請求頁碼
let newPage;
//openroute處理
if (this.openroute) {
//為url添上#page
if (page) {
history.replaceState(params.data, document.title, "#" + page);
} else {
if (history.state) {
if (!history.state.key && location.hash && location.hash.split("#") && location.hash.split("#")[1]) {
if (JSON.stringify(history.state) !== JSON.stringify(params.data)) { //選擇條件變更則請求第一頁
history.replaceState(params.data, document.title, "#1");
} else {
history.replaceState(params.data, document.title, "#" + location.hash.split("#")[1]);
}
} else {
history.replaceState(params.data, document.title, "#1");
}
} else {
if (location.hash && location.hash.split("#") && location.hash.split("#")[1]) {
history.replaceState(params.data, document.title, "#" + location.hash.split("#")[1]);
} else {
history.replaceState(params.data, document.title, "#1");
}
}
}
//獲取url后面的#page
if (location.hash && location.hash.split("#") && location.hash.split("#")[1]) {
newPage = Number(location.hash.split("#")[1]);
} else {
newPage = 1;
}
} else {
newPage = page;
}
//請求數據,獲得結果,傳遞給列表頁面
}
}
}
</script>
列表頁面獲取選擇條件
目前可能是因為框架設計的問題,沒法在請求數據之前通過Object.assign方式為替換初始變量,所以先這樣處理(笨方法,各位大佬有解決辦法麻煩指導下,謝謝):
<script>
export default {
data() {
return {
form: {
aaa: (history.state && history.state.aaa) ? history.state.aaa : null,
bbb: (history.state && history.state.bbb) ? history.state.bbb : null,
ccc: (history.state && history.state.ccc) ? history.state.ccc : null
},
};
}
};
</script>
已解決,初始變量不需要動,可以通過以下方式實現:
created(){
//獲取緩存的數據
if (history.state) {
Object.assign(this.form, history.state)
if (this.form.key) {
delete this.form.key
}
}
},
這里記錄下:之前以為created方法是在分頁組件的watch監聽之后執行的,后來發現被誤導了(因為之前是通過Object.assign(true, this.form, history.state)方式實現數據賦值的,但是并沒有成功)。下面做個小總結:
Object.assign(true, a, b);”和“Object.assign(a, b);”有什么區別?
結論:前者:改a不影響b;后者:改a影響b
分析(這篇文章有源碼分析( <font color='red'>求解答:WebStorm中如何關聯源碼?</font>),很棒):
www.jb51.net/article/150037.htm...
FAQ
history.replaceState方式是因為:它不會將更改后的url壓到history棧中,所以不會增加回退和前進的操作步數;history.replaceState方式,可存儲的state大小不能操作640k;Demo Or Source
因為是公司項目,所以目前沒有Demo或源碼
參考文章
Manipulating the browser history
總結
以上就是這篇文章的全部內容了,希望本文的內容對大家的學習或者工作具有一定的參考學習價值,如果有疑問大家可以留言交流,謝謝大家對億速云的支持。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。