//1 首先进入页面的时候需要监听浏览器的后退按钮,之后在操作的时候执行函数,
//在mounted中挂载去监听这个事件,并在methods里面添加函数,用来判断执行的条件
mounted() {
if (window.history && window.history.pushState) {
history.pushState(null, null, document.URL)
window.addEventListener('popstate', this.back, false)
}
}
// 2:需要在退出页面的时候销毁这个监听事件
destroyed() {
window.removeEventListener('popstate', this.back, false)
},
// 3: 在methods中添加方法,在这里不是使用`this.$router.go(-1)`,
因为使用返回上一步的话,方法会一直返回到第一个页面,
methods: {
back() {
this.$confirm('检测到未保存的内容,是否在离开页面前保存修改?', '确认信息', {
distinguishCancelAndClose: true,
confirmButtonText: '保存',
cancelButtonText: '放弃修改'
}).then(() => {
// this.$router.go(-1)
this.$router.back()
//this.$router.push('/about')
// this.$message({
// type: 'info',
// message: '保存修改'
// });
})
.catch(action => {
this.$message({
type: 'info',
message: action === 'cancel' ?
'放弃保存并离开页面' :
'停留在当前页面'
})
});
},
}
vue监听浏览器的后退和刷新事件
于 2023-07-05 10:09:28 首次发布
该文章描述了如何在Vue.js应用中监听浏览器的后退按钮事件,通过在`mounted`钩子中添加事件监听器,并在`destroyed`钩子中移除,确保页面离开时的适当处理。在用户尝试离开页面时,通过`$confirm`弹出对话框询问用户是否保存修改,而不是直接使用`this.$router.go(-1)`来防止直接返回到第一个页面。



1万+

被折叠的 条评论
为什么被折叠?



