代码改变世界

uniapp 页面返回询问

2025-05-23 15:55  法子  阅读(61)  评论(0)    收藏  举报

1、自定义导航栏,自定义后退函数

2、小程序:page-container。wx.enableAlertBeforeUnload和路由的routerBeforeEach,对于手势滑动返回时不做拦截,所以没用这俩

3、APP:Android使用onBackPress,iOS 禁用滑动后退

<template>
  <view>
    <u-navbar @leftClick="customBack" fixed placeholder/>
    <u-input placeholder="请输入名字" v-model="inputName"></u-input>
    <u-input placeholder="请输入手机" type="number" v-model="inputPhone"></u-input>
    <!--  #ifdef  MP-WEIXIN -->
    <view v-if="!willBack && showContainer" class="container-view">
      <page-container :show="showContainer" :overlay="false" @beforeleave="beforeleave"
        :close-on-slide-down="false"></page-container>
    </view>
    <!--  #endif -->
  </view>
</template>

<script>

export default {
  data () {
    return {
      showContainer: true,
      willBack: false,
      inputName: '',
      inputPhone: ''
    };
  },
  computed: {
    cannotBack () {
      return this.inputName || this.inputPhone
    }
  },
  // #ifdef APP-PLUS
  onBackPress (options) {
    if (options.from == 'backbutton' && this.cannotBack) { // Android 底部返回键
      this.$Router.$lockStatus = false
      this.customBack();
      return true
    } else {
      return false
    }
  },
  // #endif
  onLoad (options) {
    // #ifdef APP-PLUS
    // iOS 禁止滑动后退
    let currentWebview = this.$mp.page.$getAppWebview();
    currentWebview.setStyle({ popGesture: "none" });
    // #endif
  },
  methods: {
    customBack () {
      // 自定义返回函数
      this.beforeleave()
    },
    beforeleave () {
      if (this.cannotBack) {
        // 微信小程序: iOS 滑动后退;Android:滑动后退、底部后退
        this.willBack = true
        uni.showModal({
          title: '提示',
          content: `修改尚未保存,确认退出吗?`,
          confirmText: "确认",
          cancelText: '留在本页',
          confirmColor: '#1677FF',
          success: (res) => {
            if (res.confirm) {
              uni.navigateBack()
            } else {
              this.willBack = false
            }
          }
        })
      } else {
        uni.navigateBack()
      }
    }
  }
}
</script>