第一步:保留住搜索條件
在項目的公共數據請求方法頂部添加以下代碼:
if(options.data && options.data.holdConditions) {
window.location.replace(`${window.location.href.split('#')[0]}#${encodeURIComponent(JSON.stringify(options.data))}`)
}
options
表示請求的參數,holdConditions
表示是否需要保留頁面參數,如果需要,就將參數以hash
的方式添加在頁面的url后面,此處必須用replace
替換url
,不然返回上一頁時會需要返回兩次。- 列表頁面每次請求列表數據時,都會將搜索條件作為
url
的hash
值添加到url
的后面,給url
添加hash
值是不會刷新頁面的。 - 同時替換
url
的另一個優勢在於,詳情頁面完成操作之后,通過this.$router.go(-1)
返回列表頁面時,列表頁的url
上面會保留hash
值,可以通過解析url
直接拿到這些參數。
第二步:寫一個解析url的公共方法
// 格式化參數
export const formatSearchField = (searchField) => {
if (window.location.href.split('#').length === 2) {
let params = JSON.parse(decodeURIComponent(window.location.href.split('#')[1]))
searchField = Object.assign(searchField, params)
}
return searchField
}
第三部:解析參數,刷新列表數據
在進入頁面的時候盡早的調用第二步的公共方法解析url
,並賦值給搜索條件對象,可以在created
或者mounted
方法中進行
this.searchField = formatSearchField(this.searchField)
賦值之后就可以調用列表數據請求的函數了