首页 > 编程 > JavaScript > 正文

解决vue页面刷新或者后退参数丢失的问题

2019-11-19 14:11:04
字体:
来源:转载
供稿:网友

在toB的项目中,会经常遇到列表数据筛选查询的情景,当要打开某一项的详情页或者暂时离开列表页,再返回(后退时),选择的筛选条件会全部丢失,辛辛苦苦选择好的条件全没了,还得重新选择,如果有分页的更头大,还得重新一页页翻到之前看到的那一页,用户体验极度不友好。

我的解决有两种:

第一种方法:用vue 的<keep-alive>,即在<router-view>外套一层<keep-alive>。

虽然可以达到一定效果,但是控制起来比较麻烦,比如项目中并不是所有页面都需要缓存,代码写起来复杂

第二种方法:直接用localStorage,简单粗暴(推荐)

代码如下:

list.vue

export default {    data () {      return {        searchForm:{          project_name:'',          status:'',          city:'',          round:'',          fund:'',          charge:'',          page: 1        },      },      beforeRouteLeave(to, from, next){      //打开详情页(或者下一个任意界面)之前,把筛选条件保存到localStorage,如果离开列表页并且打开的不是详情页则清除,也可以选择不清除      if (to.name == 'Detail') {        let condition = JSON.stringify(this.searchForm)        localStorage.setItem('condition', condition)      }else{        localStorage.removeItem('condition')      }      next()    },    created(){      //从localStorage中读取条件并赋值给查询表单      let condition = localStorage.getItem('condition')      if (condition != null) {       this.searchForm = JSON.parse(condition)      }      this.$http.get('http://example.com/api/test', {params: this.searchForm})      .then((response)=>{        console.log(response.data)      }).catch((error)=>{        console.log(error)      })    }  }}

这种方法也受限于localStorage的局限性,不过可以通过使用cookie来弥补,具体不再详述。

以上这篇解决vue页面刷新或者后退参数丢失的问题就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持武林网。

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表