在mounted, 添加监听,在beforeDestroy,移除监听
login, Main 是路由页面,根据自己的项目修改。
mounted() {
document.addEventListener('backbutton', this.backbutton,false)
},
beforeDestroy(){
document.removeEventListener('backbutton', this.backbutton,false)
},
methods:{
backbutton() {
if (this.time == 0) {
this.time = (new Date()).getTime(); // 2s内再次点击就退出
}
// 监听返回按钮
var url = location.href.split('#')[1];
url = url.substring(1);
//alert(url)
// var urlList = location.href
if(url==='login'||url==='Main'){ // 处于app首页,满足退出app操作
let tmpTime = (new Date()).getTime();
let isShort = (tmpTime-this.time<4000)
if(isShort && this.backClick!=0){
navigator.app.exitApp();
}else if(isShort){
this.backClick++;
}else{
this.backClick = 0
}
Toast({
message: '再按一次退出程序',
position: 'bottom',
duration: 2000
});
this.time = tmpTime;
return;
}else{
this.backClick = 0;
history.back()
}
},
}