先看效果圖:
1.刷新頁面效果:
2.跳轉路由(進入別的頁面前)效果:
代碼:
// 路由跳轉確認 beforeRouteLeave(to, from, next) { const answer = window.confirm("當前頁面數據未保存,確定要離開?"); if (answer) { next(); } else { next(false); } }, // 瀏覽器刷新確認 把下面 '/test' 換成需要確認操作效果的頁面路徑,可以通過注釋window.onbeforeunload函數后在控制台查看console mounted() { var _this=this; console.log(_this.$route.fullPath) window.onbeforeunload = function(e) { if (_this.$route.fullPath == '/test') { e = e || window.event; // 兼容IE8和Firefox 4之前的版本 if (e) { e.returnValue = "關閉提示"; } // Chrome, Safari, Firefox 4+, Opera 12+ , IE 9+ return "關閉提示"; } else { window.onbeforeunload = null; } }; }