使用history保存列表页ajax请求的状态
问题最近碰到两个问题:
然后点击浏览器“后退”按钮就直接返回到首页,实际这里想要的效果是返回列表页上一页。
优化前代码
const currentChange = (currentPage) => { ajax(`请求地址/${currentPage}`) .then(renderPage) } history经过几番搜索,发现可以用History 接口来实现我们想要功能。 history.pushState()按指定的名称和URL(如果提供该参数)将数据push进会话历史栈,数据被DOM进行不透明处理;你可以指定任何可以被序列化的javascript对象。具体描述可以参考 文档 通过history.pushState(state,title,url)可以修改会话历史栈,把我们需要保存的数据存到state中,这里我们存入一个对象,属性为当前页数;title一般没什么用,这里传入null;url会修改当前历史纪录的地址,浏览器在调用pushState()方法后不会去加载这个URL 假设当前currentPage为1,当前url为www.example.com/search/index ... const pushState = () => { const url = `/search/index/${currentPage}` history.push({ page: currentPage },null,url) } const currentChange = (currentPage) => { ajax(`请求地址/${currentPage}`) .then(res =>{ pushState(currentPage) renderPage() }) } ... 现在代码执行顺序是:页数改变 => ajax请求 => pushState => renderPage() window.onpopstate现在我们通过history.pushState()方法把状态存入历史会话中了,接下来就要监听window.onpopstate事件 参考mdn文档 window.onpopstate 接下来监听这个事件 window.addEventListener("popstate",(event) => { if(event.state !== null){ page = event.state.page changeCurrentPage(page) // 修改当前页数 } }) 当popstate触发时,会修改当前页数,然后触发之前定义的currentChange方法,更新数据,渲染页面。 问题2到此为止,问题1就解决了。 mounted () { ajax(location.href) } 这样就完成了。当然如果你的状态比较复杂,可以把数据存入本地Storage,添加一些判断即可 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |