需求背景:项目中需要做一个返回确认,避免用户误触返回键而退出当前页面。需求背景:原理:利用history和浏览器刷新popstate状态原理:实现:实现:1、在mounted() 阶段判断并添加popstate事件监听,History.pushState()(参数:一个状态对象,一个标题(现在被忽略了),以及一个可选的URL地址), 注意:IOS版的微信,是会立即触发popstate事件,所以需要pageshow做下处理,(当一条会话历史记录被执行的时候将会触发页面显示(pageshow)事件。(这包括了后退/前进按钮操作,同时也会在onload 事件触发后初始化页面时触发))2、在methods里定义监听操作函数3、页面销毁时,取消监听。(注意:一定要取消监听,否则其他vue路由页面也会被监听)补充知识:vue项目监测浏览器返回按钮补充知识:补充知识:vue项目监测浏览器返回按钮在WebApp或浏览器中,会有点击返回、后退、上一页等按钮实现自己的关闭页面、调整到指定页面、确认离开页面或执行一些其它操作的需求。可以使用 popstate 事件进行监听返回、后退、上一页操作。简单介绍history中的操作简单介绍history中的操作window.history.back(),后退window.history.forward(),前进window.history.go(num),前进或后退指定数量历史记录window.history.pushState(state,title,url),在页面中穿件一个history实体。直接添加到历史记录中。参数: state:储存一个对象,可以添加相关信息,可以使用history.state读取其中的内容。title: 历史记录的标题,url:创建的历史记录rul,进行历史记录操作时会跳转到该链接。window.history.replaceState(),修改当前的history实体。popstate事件,history实体改变时触发事件window.history.state,会获得history实体中的state对象。使用方法使用方法取消默认的返回操作添加一条history实体作为替代原来的history实体
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);
},
methods:{
goBack(){
this.$router.replace({path:'/'});
//replace替换原路由,作用是避免回退死循环
}
}
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);
},
methods:{
goBack(){
this.$router.replace({path:'/'});
//replace替换原路由,作用是避免回退死循环
}
}以上这篇在vue项目中利用popstate处理页面返回的操作介绍就是小编分享给大家的全部内容了,希望能给大家一个参考。