【问题标题】:Vue.js redirect to a new page/component if F5 is pressed如果按下 F5,Vue.js 将重定向到新页面/组件
【发布时间】:2018-08-15 16:10:01
【问题描述】:

这里是 vue.js 的新手。 我已经部署了一个包含 3 个组件的完整表单网站:Id、Form 和 End

一切运行良好!我只在一个动作上挣扎。

如果用户在组件 /Form 上按 F5 重新加载页面,则页面变为空白......这是一个非常糟糕的体验......我所做的是,我添加了一个 window.onbeforeunload 动作,它将显示一个弹出窗口,询问用户是否真的想离开页面。如果用户回答“离开”,我希望页面重定向到 /Id。

当前情景是: /Id ---> /Form ---> F5 ---> 弹出确认离开页面 --yes--> /Form(空白页)

我想要的是: /Id ---> /Form ---> F5 ---> 弹出确认离开页面 --yes--> /Id

当我如下运行 window.onbeforeunload 时,它运行良好:

window.onbeforeunload = function(){
    return "Are you sure?";
}

但是当我尝试使用 window.onbeforeunload 和 this.$router.push('/Id') 的组合时,它似乎根本不起作用......或者我做错了。

这是我尝试添加的方法。$router.push('/Id') :

<script>
import axios from 'axios'
var answer =''

window.onbeforeunload = function(){
  var answer = confirm('Are you sure?');
  if (answer == 'true'){
    this.$router.push('/Id')
  }
  return answer;
}

export default {
  data () {
    return {
      
      form: {
        ....
      },
    }
  },
  
  methods: {
    ....
    }
   ....
   ...
 ...

【问题讨论】:

  • 你能显示你使用this.$router.push('/Id')的代码吗?
  • 我用 this.$router.push('/Id') 使用的代码更新了我的帖子。基本上我尝试检索弹出窗口的答案,如果用户说“是离开”然后推送到 /Id
  • 即使使用 window.location="URL" 也不起作用... window.onbeforeunload = function(){ var answer = confirm('Do you want to quit ?'); if (answer){ window.location="yahoo.com" } 返回答案; } 弹出消息出现 - 我回答“离开”。但后来我得到一个空白页....
  • 页面空白时的数据是什么样的?使用该数据来确定页面是否为空白,如果是则在created钩子中重定向

标签: javascript vue.js onbeforeunload


【解决方案1】:

好的,我找到了一种在桌面上使用以下代码的方法:

var
  is_asked = false;

window.onbeforeunload = 
  function (ev) {
    var e = ev || window.event;
    window.focus();
    if (!is_asked){
      is_asked = true;
      var showstr = "CUSTOM_MESSAGE";
      if (e) {  //for ie and firefox
        e.returnValue = showstr; 
      }
      return showstr; //for safari and chrome
    }
  };

window.onfocus =
  function (ev){
    if (is_asked){
      window.location.href = "http://localhost:8080";
    }
  }

但我的手机仍然没有运气......

当我在桌面上使用 safari 时,它运行良好,但是当我在移动设备上使用 safari 时,我又得到一个空白页面。我认为手机不支持与window.onbeforeunload相关的东西?

【讨论】:

    【解决方案2】:

    我通过使用本地存储解决了这个问题。

    我没有重定向到主页,而是将表单数据存储在本地存储中,现在一切正常 - https://www.npmjs.com/package/vue-localstorage

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-06-10
      • 2011-09-26
      • 2013-05-24
      • 1970-01-01
      • 2016-11-05
      • 2013-02-14
      • 2019-04-16
      相关资源
      最近更新 更多