【问题标题】:How to detect the user comes back to a page rather than starts browsing it?如何检测用户返回页面而不是开始浏览?
【发布时间】:2019-03-28 21:57:43
【问题描述】:

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

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

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

1/ 使用路由器滚动行为

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

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

2/ 使用 url 参数

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

【问题讨论】:

    标签: vue.js


    【解决方案1】:

    历史组件

    // 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)
       }
    }
    

    数据方式

    save the information in the browser

    // 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)
       }
     }
    }
    //...
    

    use statemanagement

    // 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)
       }
     }
    }
    //...
    

    use globals

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

    【讨论】:

    • 我的问题是关于检测用户是来到页面还是返回页面。假设我们有几页:P1、P2、P3、P4。当用户从 P1 导航到 P2 时,P2 开始一个新的流程。当他们进入 P3 再回到 P2 时,我希望收到通知,他们回来了。
    • 哦,好吧 - 这就是你要找的东西:vuejs.org/v2/api/#keep-alive ?
    • Keep alive 不会在您更改组件时存储页面状态。当我导航到另一个页面时会发生这种情况。无论如何,这不是我所追求的。我只想在用户返回浏览历史记录中的某个页面时收到通知。
    • 我添加了一些历史组件的草图,它将触发@visited 事件
    • 感谢您的努力。假设我们有 Link、Page1(它有你的代码)、Page2。通过单击链接,用户导航到 Page1,然后导航到 Page2,然后返回到 Page1。没关系,你的代码有效。但是,当用户关注 Link、Page1、Page2、Link、Page1 时它会失败,因为它说用户已经回到 P1,这是不正确的。
    猜你喜欢
    • 1970-01-01
    • 2018-08-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-12-20
    • 2023-03-19
    • 2014-09-16
    • 2013-05-28
    相关资源
    最近更新 更多