解决思路:进入页面的时候获取初始页面历史记录数量,返回的时候获取当前页面历史记录数量,两者数量差即为页面返回层数(uniapp 的 getCurrentPages 获取的页面栈跟浏览器实际历史记录是不一致的)。
onLoad() {
this.initPageNum = 0
// #ifdef H5
this.initPageNum = window.history.length
// #endif
},
methods: {
back() {
let currentPageNum = 0
// #ifdef H5
currentPageNum = window.history.length
// #endif
// +1 是因为要返回到初始页面的上一层
uni.navigateBack({
delta: currentPageNum - this.initPageNum + 1
})
}
}