//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 首次发布