首页 > 解决方案 > 当浏览器的后退按钮在Vue.js中传递时如何触发警报

问题描述

一旦用户单击网页的后退按钮,我就会尝试触发警报消息。我正在尝试以下方式:

import LeavePopup from '../../global/js/leave-popup';
import ScrollTo from '../../global/js/scroll-to';
import UrlHandler from '../../global/js/url-handler';

import Vue from 'vue';
import SignUpForm from '../../global/js/components/SignUpForm';
import VideoPlayer from '../../global/js/components/VideoPlayer';
import JustMadeMoney from '../../global/js/components/JustMadeMoney';
import Carousel from 'vue-owl-carousel'

document.addEventListener("DOMContentLoaded", function (event) {
    LeavePopup.bind('.modal');
    ScrollTo.bind();
    UrlHandler.handle('additionalParams');
});

new Vue({
    el: '#app',

    components: {
        VideoPlayer,
        SignUpForm,
        Carousel,
        JustMadeMoney
    },
    mounted() {
        // if back button is pressed
        window.onpopstate = function(event) {
          alert("Back button clicked");
        };
     }
});

但目前没有任何反应,我怎样才能正确捕捉到后退按钮的点击?

标签: javascriptvue.js

解决方案


研究使用导航守卫。根据 vue-router文档

The leave guard is usually used to prevent the user from accidentally leaving the route with unsaved edits. The navigation can be canceled by calling next(false).

下面的示例来自 Vue 文档。您可以修改它以满足您的需要。

beforeRouteLeave (to, from, next) {
  const answer = window.confirm('Do you really want to leave? you have unsaved    changes!')
  if (answer) {
    next()
  } else {
    next(false)
  }
})

支持上述方法

这篇文章使用了不同的方法。


推荐阅读