H5退出时所遇到的问题:
1。按返回键或anroid手机的物理返回键时,都不走destroy方法。
2。按物理返回键,添加popstate监听时,
(1)历史记录要准确,否则会执行多次监听方法
(2)进入子页面,监听没有及时移除,子页面也被监听了。
最近新做了个项目,需要在首页destroy的时候,调用接口更新数据,但是按返回键或anroid手机的物理返回键时,并不走destroy方法。
1。当按页面的返回箭头时的处理:
backReturn () {this.$router.go(-1)this.$refs.myEnergy.destroySelf()},
按页面的返回箭头时,调用子组件的更新数据的方法;
2。按anroid物理返回键时,在网上查了很多资料,都是要添加监听,而且是当窗口历史记录改变时的监听,需要将历史记录一下。
我首先采用的方法:
mounted(){if (window.history && window.history.pushState) {history.pushState(null, null, document.URL);window.addEventListener('popstate', this.goBack, false);}},
但采用这种方法存在一些问题,当我点击其他按钮跳转到子页面再返回来,再按退出键时,监听方法会跑2次。
采用下面的方法可以解决这个跑2次的问题:
mounted () {if (window.history && window.history.pushState) {// history.pushState(null, null, document.URL)this.pushHistory()window.addEventListener('popstate', this.backListener, false)}},beforeDestroy () {console.log('beforeDestroy', '3333')window.removeEventListener('popstate', this.backListener)},methods: {pushHistory () {var state = {title: 'title',url: '#'}window.history.pushState(state, null, '#')},backListener () {alert('77777')this.backReturn()},backReturn () {this.$router.go(-1)this.$refs.myEnergy.destroySelf()window.removeEventListener('popstate', this.backListener)},}
这种方法虽然能解决上面所说的跑2次的问题,但当按页面的返回箭头时,backReturn方法会走2次。一次按钮事件,一次监听,而且进入子页面,子页面也被添加了监听(虽然在destroy之前把监听给移除了,但由于子页面的created方法运行在父页面的beforeDestroy方法之前,所以子页面也被监听了。
最终解决:
采用监听onpagehide页面隐藏事件来处理。代码如下:
mounted () {//挂载完成后,判断浏览器是否支持popstateif (window.history && window.history.pushState) {window.addEventListener('pagehide', this.backListener, false)}},// 页面销毁时,取消监听。否则其他vue路由页面也会被监听beforeDestroy () {window.removeEventListener('pagehide', this.backListener)},methods: {// 将监听操作写在methods里面,removeEventListener取消监听内容必须跟开启监听保持一致,所以函数拿到methods里面写backListener () {this.$refs.myEnergy.destroySelf()},}
如果觉得《VUE 物理返回键的处理》对你有帮助,请点赞、收藏,并留下你的观点哦!