前言
本文主要介绍Vue使用History记录上一页数据的相关内容。vue使用历史后,可以让url更美观,也就是不再有“#”的问题。下面就不多说了。让我们来看看详细的介绍
用户界面
需求
从列表页的第二页进入详情页,返回时列表页仍显示在第二页;
从列表页的第二页进入详细页,返回时列表页的过滤条件仍然存在。
!-更多-
技术选择
通过这个使用vue路由器组件。$ router.push ({path:path,query : query });在url中存储页码和选择条件作为参数的方法在上面的UI设计中是可行的,但是当列表页中包含了tab组件(分页组件很常见)时,推送会带来一些问题(PS:也可能是我的技术能力所致)。使用历史API(html 5支持)将页码作为参数存储在url中,选择条件存储在历史中(不清楚数据存储在哪里);按位置获取页码。根据历史记录获取存储的选择标准。说明具体实现-技术选择2
转换
为分页组件添加一个开关(openroute),因为它需要灰度在线,如果有问题,只有一个页面需要调整。代码如下:
脚本导出默认值{ props : { open route : { type : boolean,default : ()=(true)}},}/页码存储在脚本分页组件中,并通过选择标准获得
脚本导出默认{ methods : { fetch data(page){//request params let params=this . params;//请求页码让newPage//openroute处理if(this . open route){//add # page if(page){ history。将状态(params.data,document.title,' #' page)替换为url} else { if (history.state) { if(!history . state . key location . hash location . hash . split(“#”)location . hash . split(“#”)[1]){ if(JSON . stringify(history . state)!==JSON。Stringify(参数。data)){//如果选择条件改变,请求首页历史。replacestate(参数。数据,文件。标题,' # 1 ');} else { history . replace state(params . data,document.title,' # ' location . hash . split(' # ')[1]);} } else { history . replace state(params . data,document.title,' # 1 ');} } else { if(location . hash location . hash . split(' # ')location . hash . split(' # ')[1]){ history . replace state(params . data,document.title,' # ' location . hash . split(' # ')[1]);} else { history . replace state(params . data,document.title,' # 1 ');} } }//获取url后的# page if(location . hash location . hash . split(' # ')location . hash . split(' # ')[1]){ new page=number(location . hash . split(' # ')[1];} else { NewPage=1;} } else { newPage=page}//请求数据,获取结果,并将其传递到列表页} } }/脚本列表页以获取选择条件
目前可能是因为框架设计的问题,无法在请求数据之前用Object.assign替换初始变量,所以先这样处理(笨方法,大家都有解决方案,谢谢):
脚本导出默认值{ 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 } },这里记录的是认为创建的方法是在分页组件的watch monitoring之后执行的,但是发现被误导了(因为数据赋值是通过object的方式实现的。赋值(true,this。形式,历史。陈述)之前,但不成功)。下面我们来做个小总结:
Object.assign(true,a,b);和“对象分配(a,b);“有什么区别?
结论:前者:改变A不影响B;后者:改变A影响b。
分析(本文有源代码分析(font color='red '):如何在WebStorm中关联源代码?/font),太好了):
www.jb51.net/article/150037.htm.
常见问题解答
之所以需要使用history.replaceState,是因为它不会将更改后的url推送到历史堆栈中,所以不会增加向后和向前操作的步骤数;以history.replaceState的方式,可存储状态大小不能在640k下操作;可能存在浏览器兼容性问题,请点击这里:https://caniuse.com/#feat=his.演示或来源
因为是公司项目,目前没有Demo或者源代码
参考文章
操作浏览器历史记录
摘要
以上就是本文的全部内容。希望本文的内容对大家的学习或工作有一定的参考价值。有问题可以留言交流。谢谢你的支持。