【问题标题】:How to detect page is refreshed on vue?如何检测页面在vue上刷新?
【发布时间】:2020-02-18 01:23:25
【问题描述】:

我尝试这样:

created() {
      window.addEventListener('beforeunload', function(event) {
         event.returnValue = 'Write something'
         this.$router.push('/')
      })
    },

这样的消息:

如果我点击取消,它将取消

如果我单击重新加载,它将重新加载页面。它重新加载到详细页面

我希望当用户单击重新加载按钮时它会重新加载页面。但将页面重新加载到主页

我该怎么做?

更新

我的路由器是这样的:

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 我读过它,但没有帮助。你可以看看我的代码。它是一样的。但这无济于事
  • 听起来您在路由器中使用 history 模式并且没有启用适当的 URL 重写。你的环境和配置是什么?
  • @Phil 我更新了我的问题

标签: javascript vue.js vue-component vuetify.js page-refresh


【解决方案1】:

您可以将Vue生命周期的created钩子添加到编写新Vue实例的main.js中。

这是正确的地方,当您刷新应用程序时,它会再次重新初始化 Complete Vue 应用程序。

如果你在浏览器中使用后退或前进,或者

this.$router.go(-1)

不考虑刷新,保留vue应用的状态

这样使用,这里page3是浏览器当前页面,如果你想刷新,它会提示确认ro reload this site。如果是,它会重新加载到主页(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');
      }
    }          
   }
  }
})

更新代码: 根据问题,如何从重新加载中检测页面,上述逻辑工作正常

但是如果用户想要阻止页面重新加载并要求 用户在刷新或重新加载页面前确认,下面的代码就是答案。

下面的逻辑是,如果用户在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() {
    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');
      }
    }
  }
})

【讨论】:

    猜你喜欢
    • 2011-05-16
    • 2011-12-22
    • 2018-10-06
    • 2020-12-11
    • 2018-10-27
    • 2018-05-02
    • 2012-01-04
    • 2010-11-29
    • 1970-01-01
    相关资源
    最近更新 更多