当前位置: 首页 > Web前端 > HTML5

监听浏览器的退回按钮与项目返回按钮结合,若编辑信息时未保存,返回会有提示

时间:2023-04-05 12:41:51 HTML5

监控浏览器的后退按钮与项目后退按钮相结合。如果编辑时没有保存信息,返回时会有提示。、调整到指定页面、确认离开页面或进行其他操作。您可以使用popstate事件来监视返回、后退和上一页操作。pushState()的基本参数有:window.history.pushState(state,title,url);state:存储一个对象,可以添加相关信息,可以使用history.state读取内容。title:历史记录的标题(目前浏览器不支持)。url:指向已创建历史记录的链接。执行历史操作时,您将被重定向到此链接。pushState()配合popstate监听如果想很好的支持浏览器历史向前向后操作,应该部署popstate监听:window.addEventListener('popstate',function,false);具体实现逻辑:mounted(){if(window.history&&window.history.pushState){//当前页面插入到历史记录中(必须,否则浏览器无法识别)history.pushState(null,null,document.URL)window.addEventListener('popstate',this.goBack,false)}}destroyed(){window.removeEventListener('popstate',this.goBack,false)},//每次路由都会触发这个方法returnsgoBack(){if(this.isSave){window.history.back()return}//console.log("点击了浏览器的后退按钮")if(this.$route.params.edit==='edit'&&(JSON.stringify(this.contracts.form)!==JSON.stringify(this.temp_data))){this.$confirm('当前内容尚未保存,确定关闭',{confirmButtonText:'确定',cancelButtonText:'取消',类型:'警告'}).then(()=>{window.history.back()}).catch(()=>{//每次返回都会消费一个历史实体,如果用户选择取消离开,需要继续pushState一个entity;history.pushState(null,null,document.URL)console.log('Cancel')})}else{window.history.back()}},实现效果: