首页 > 解决方案 > 如何检测用户返回页面而不是开始浏览?

问题描述

我有一个网格组件,我在我的应用程序的许多路线中使用它。我想保持它的状态(即分页,搜索参数)并在用户返回网格时恢复它(即从编辑一行)。另一方面,当用户启动新流程(即通过单击链接)时,页面将设置为零,并使用默认参数调用 Web 服务。

我如何识别用户确实回来而不是开始新流程?

当我研究这个问题时,我遇到了以下解决方案。不幸的是他们没有为我服务

1/ 使用路由器滚动行为

scrollBehavior(to, from, savedPosition) {
to.meta.comeBack = savedPosition !== null;
}

它确实告诉我用户是否回来。不幸的是,滚动行为在网格的创建和挂载钩子被调用之后运行。这样我就没有地方放我的代码来恢复状态了。

2/ 使用 url 参数

网格的路线将有一个可选参数。当参数为空时,代码会知道这是一个新流程并使用 $router.replace 例程设置一个新流程。然后用户会去编辑,回来,代码会知道他们回来了,因为路由参数!= null。问题是调用 $router.replace 会重新创建组件(即调用钩子等)。此外,可选参数会混淆 vue-router 与路由中的其他可选参数。

标签: vue.js

解决方案


历史部分

// component ...
// can error and only serves the purpose of an idea
data() {
  return {
     history: []
  }
},
watch: {
  fullRoute: function(){
      this.history.push(this.fullRoute);
      this.$emit('visited', this.visited);
  }
},
computed: {
 fullRoute: function(){
    return this.$route.fullPath
 },
 visited: function() {
     return this.history.slice(-1).includes(this.fullRoute)
   }
}

数据方式

将信息保存在浏览器中

// component ...
// can error and only serves the purpose of an idea
computed: {
 gridData: {
   get: function() {
     return JSON.parse(local.storage.gridData) 
   },
   set: function(dataObj){
     local.storage.gridData = JSON.stringify(dataObj)
   }
 }
}
//...

使用状态管理

// component ...
// can error and only serves the purpose of an idea
computed: {
 gridData: {
   get: function() {
     return this.$store.state.gridData || {} 
   },
   set: function(dataObj){
     this.$store.dispatch("saveGrid", gridData)
   }
 }
}
//...

使用全局变量

// component ...
// can error and only serves the purpose of an idea
computed: {
 gridData: {
   get: function() {
     return window.gridData || {} 
   },
   set: function(dataObj){
     window.gridData = dataObj
   }
 }
}

推荐阅读