【Uni-App】uniapp-H5页面刷新后返回失效,页面栈清空问题,navigateBack失效问题

问题描述

在打包生成的H5项目里,刷新后,页面回调,这时候使用uniapp原生的返回api方法会失效。uni.navigateBack()

原因分析:

由于页面回调后导致当前页面刷新,使用getCurrentPages()方法获取页面栈只有当前页面页面无法返回,一直在当前页面刷新闪烁。

解决方案:

想到的解决方案使用原生js的history对象,封装一个兼容uniapp api和原生js的返回的方法。

const navigateBack = (params) => {
    
    
	const pages = getCurrentPages()
	if (pages.length === 1) {
    
    
		if (typeof params === 'number') {
    
    
			history.go(-params)
		} else {
    
    
			history.back()
		}
	} else {
    
    
		uni.navigateBack()
	}
}

全局封装组件:

<template>
	<view>
		<view class="toBack" >
			<image class="arrow-icon" src="https://image.3rdplanet.cn/upload/banner/icon_fh_16pt%403x.png" @click="navigateBack"></image>
      <view class="title"> {
    
    {
    
    title}}</view>
      <view class="more"> </view>
		</view>
	</view>
</template>

<script>
	export default{
    
    
		props:{
    
    
			url:{
    
    
				type:String,
				default:()=>{
    
    
					return ''
				}
			},
      title:{
    
    
        type:String,
				required:false,
        default:''
      }
		},
		methods:{
    
    
      /**
        * @description: H5 App通用方案 解决H5刷新返回失败问题
        * @param {*} params
        */
		navigateBack(params) {
    
    
	        const pages = getCurrentPages()
	        if (pages.length === 1) {
    
    
	          if (typeof params === 'number') {
    
    
	            history.go(-params)
	          } else {
    
    
	            history.back()
	          }
	        } else {
    
    
	          uni.navigateBack()
	        }
     	}
		}
	}
</script>

<style scoped lang="less">
	.toBack{
    
    
    box-sizing: border-box;
    display: flex;
    justify-content: space-between;
    padding: 24rpx 20rpx;
		width: 100%;
		height: 96rpx;
		background-color: #FFFFFF;
		text-align: center;
		font-size: 32rpx;
		font-weight: 400;
		color: #333333;
	  border-top: 1px solid #FFF8F8F8;
    .arrow-icon{
    
    
      width: 32rpx;
      height: 32rpx;
      margin: auto 0;
      line-height: 32rpx;
    }
	}
	
</style>

猜你喜欢

转载自blog.csdn.net/weixin_48200589/article/details/127092147