最近在做一个用 Vue + Cordova + Vant.UI 做移动端APP,遇到这样一个问题,只要页面是在主路由页面,按一次返回,就会直接退出APP,感觉这个使用起来体验感很差,于是看了一下常见的APP里有'再点一次退出'这样的功能,尝试着自己也优化一下。
案例:
一、添加Cordova插件
安装Cordova中物理返回按键的插件
cordova plugin add cordova-plugin-backbutton
安装Cordova中退出App的插件
cordova plugin add cordova-plugin-exitapp
注:Vant.UI的使用就不在此赘述了,可以参考Vant.UI中文官网
二、在vue的main.js中添加
注:只会在以下声明的路由页面中拥有该功能,其余页面的返回功能均不受影响。
document.addEventListener('deviceready', function () {
let vueInstance = new Vue({
router,
store,
render: h => h(App)
}).$mount('#app')
let time;
//监听手机返回按键
document.addEventListener("backbutton", function () {
let intervalTime = new Date() - time;
// 判断页面(在为以下页面时拥有"再按一次退出"功能)
if (
vueInstance.$route.name.toString() === "login" ||
vueInstance.$route.name.toString() === "1" ||
vueInstance.$route.name.toString() === "2" ||
vueInstance.$route.name.toString() === "3" ||
vueInstance.$route.name.toString() === "4" ||
vueInstance.$route.name.toString() === "5"
) {
//两次按键间隔时间小于1秒退出APP
if (intervalTime < 1000) {
navigator.app.exitApp();
} else {
//刷新time
time = new Date();
Toast({
message: "再按一次退出~",
position: "bottom",
duration: 1000
})
}
} else {
//在其他页面时返回上一页面
vueInstance.$router.back(-1);
}
}, false);
}, false);