第一步:保留住搜索条件
在项目的公共数据请求方法顶部添加以下代码:
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)
赋值之后就可以调用列表数据请求的函数了