在 Android 設備上,你可以通過監聽物理返回鍵來實現特定的邏輯。這可以通過在 Vue 組件中添加一個事件監聽器來實現:
mounted() {
this.$once('hook:beforeDestroy', () => {
if (document.removeEventListener) {
document.removeEventListener('backbutton', this.onBackKeyDown, false);
} else if (window.removeEventListener) {
window.removeEventListener('backbutton', this.onBackKeyDown, false);
}
});
if (document.addEventListener) {
document.addEventListener('backbutton', this.onBackKeyDown, false);
} else if (window.addEventListener) {
window.addEventListener('backbutton', this.onBackKeyDown, false);
}
},
methods: {
onBackKeyDown() {
// 處理返回鍵邏輯,例如導航到上一個頁面或顯示確認對話框
this.$router.go(-1); // 返回上一個頁面
// 或者使用 this.$router.push('/your-path') 導航到特定頁面
}
}
檢查頁面生命周期
確保在頁面的?
beforeDestroy
?或?destroyed
?鉤子中正確移除事件監聽器,以避免內存泄漏或重復監聽問題:beforeDestroy() {
if (document.removeEventListener) {
document.removeEventListener('backbutton', this.onBackKeyDown, false);
} else if (window.removeEventListener) {
window.removeEventListener('backbutton', this.onBackKeyDown, false);
}
}