如何在vue中检测页面是否被刷新?

7
我尝试这样做:
created() {
      window.addEventListener('beforeunload', function(event) {
         event.returnValue = 'Write something'
         this.$router.push('/')
      })
    },

这条信息如下图所示:

enter image description here

如果我点击取消,它将会取消操作。

如果我点击重新加载,它将重新加载页面,而且会跳转到详细页面。

我想让用户点击重新加载按钮时,页面会重新加载但会跳回首页,怎么实现呢?

更新:我的路由器如下图所示:

import Vue from 'vue'
import Router from 'vue-router'
import Home from './views/Home.vue'
...

Vue.use(Router)

export default new Router({
  mode: 'history',
  base: process.env.BASE_URL,
  routes: [
    {
      path: '/',
      name: 'home',
      component: Home
    },
    ...
  ]
})

我的环境:开发环境

我的项目正在使用Vuetify。


@Graham 我已经阅读了它,但没有帮助。你可以看到我的代码,它是一样的。但是它没有帮助。 - moses toh
听起来你正在路由器中使用“history”模式,但没有启用适当的URL重写。你的环境和配置是什么? - Phil
@Phil,我已经更新了我的问题。 - moses toh
1个回答

7
您可以将Vue生命周期的created钩子添加到编写新Vue实例的main.js中。
当您刷新应用程序时,这是正确的位置,它会重新初始化完整的Vue应用程序。
如果您在浏览器中使用后退或前进按钮,或者...
this.$router.go(-1)

不算刷新,Vue应用程序的状态会被保留。

使用方法如下:此处page3是浏览器当前页面,如果您想要刷新,则会提示确认重新加载此站点。如果选择“是”,则将重新加载到主页(page1),否则将停留在相同页面。

在main.js中

import Vue from 'vue'
import App from './App'
import router from './router'
import store from './store'

Vue.config.productionTip = false


new Vue({
  el: '#app',
  router,
  store,
  components: { App },
  template: '<App/>',
  created() {
    if (performance.navigation.type == 1) {
      if(this.$route.path == '/page3') {
        if (confirm('Reload site?. Change you made may not be saved.')) {
          this.$router.push({path: '/page1'})
        } else {
          console.log('reload page now');
      }
    }          
   }
  }
})

代码更新: 根据问题“如何检测页面重新加载”,上述逻辑可以正常工作。

但是,如果用户想要防止页面重新加载并在刷新或重新加载页面之前向用户请求确认,则以下代码是答案。

以下逻辑是这样的:如果用户在页面3中并尝试刷新或重新加载页面,则会提示用户确认并重定向到主页(页面1)。如果用户取消刷新,则不会重新加载并保留页面状态。

在main.js文件中。

import Vue from 'vue'
import App from './App'
import router from './router'
import store from './store'
Vue.config.productionTip = false


new Vue({
  el: '#app',
  router,
  store,
  components: { App },
  template: '<App/>',
  created() {
    var self = this;
    window.onbeforeunload = function (e) {
      if(self.$route.path  == "/page3") {
        e = e || window.event;
        //old browsers
        if (e) {e.returnValue = 'Changes you made may not be saved';}
        //safari, chrome(chrome ignores text)
        return 'Changes you made may not be saved';
      } else { 
        return null;
      }
    };
    if (performance.navigation.type == 1) {
      if(this.$route.path == '/page3') {
          this.$router.push({path: '/page1'})
        } else {
          console.log('reload page without redirect');
      }
    }
  }
})

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接