javascript - 当浏览器的后退按钮在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");
};
}
});
但目前没有任何反应,我怎样才能正确捕捉到后退按钮的点击?
解决方案
研究使用导航守卫。根据 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)
}
})
本帖支持上述方法
这篇文章使用了不同的方法。
推荐阅读
- operating-system - 硬件运行时操作系统(操作系统)是否在运行?
- javascript - 如何过滤掉数组之间的匹配,并添加一个额外的键/值?
- redux - React-Redux Action 成功调度但返回 undefined
- python - Python:同时读取两个文件,但从第二行开始读取第二个文件
- c# - 如何从 asp.net webforms 调用安全的 azure 函数?
- java - ExecutorService - 如何在其中一个发生异常后中断已从主线程调用的线程的执行
- python - Pandas groupby 按一列求和,按另一列排序结果
- r - 拆分数据框 R
- python - 与来自多个字典的给定键对应的一组值的交集
- get - JS 将 XMLHttpRequest 转换为 Fetch 函数 (GET):无法在“窗口”上执行“获取”:使用 GET/HEAD 方法的请求不能有正文