ArmLiang
ArmLiang
  • 发布:2025-10-27 15:42
  • 更新:2025-10-27 15:42
  • 阅读:13

解决uniapp打包h5刷新页面无法返回上一级页面的问题

分类:uni-app

h5环境直接拦截默认的返回方法,使用router自带的返回

拦截默认的pageHead的返回方法,判断整个页面的history

import Vue from 'vue'  
if (process.env.VUE_APP_PLATFORM === 'h5') {  
  // 替代默认的返回api  
  uni.navigateBack = function (params: any) {  
    let canBack = true  
    const pages = getCurrentPages()  
    let delta = params?.delta  
    if (typeof delta !== 'number') delta = 1  

    const router = getApp().$router  
    if (pages.length) {  
      const from = 'navigateBack'  
      function hasLifecycleHook(options: any, hook: string) {  
        return Array.isArray(options[hook]) && options[hook].length  
      }  
      const page = pages[pages.length - 1] as any  
      if (  
        hasLifecycleHook(page.$options, 'onBackPress') &&  
        page.__call_hook('onBackPress', {  
          from,  
        }) === true  
      ) {  
        canBack = false  
      }  
    }  
    if (canBack) {  
      if (delta > 1) {  
        router._$delta = delta  
      }  
      router.go(-delta, {  
        animationType: '',  
        animationDuration: '',  
      })  
    }  
  }  
  // 修复 自带的pageHead 刷新点击右上角回到首页  
  const Page = Vue.component('Page')  
  const PageHead = Page.component('PageHead')  
  // @ts-ignore  
  PageHead.methods._back = function () {  
    if (history.length === 1) {  
      return uni.reLaunch({  
        url: '/',  
      })  
    } else {  
      return uni.navigateBack({  
        // @ts-ignore  
        from: 'backbutton',  
      })  
    }  
  }  
}  
0 关注 分享

要回复文章请先登录注册