0
点赞
收藏
分享

微信扫一扫

微信小程序实现监听点击返回挽留弹框功能(支持h5+uniapp)

 核心就是用 page-container这个组件

<template>
  <!-- #ifdef MP-WEIXIN -->
  <!-- 微信小程序使用page-container方式拦截返回 -->
  <page-container
    :show="showPageContainer"
    :duration="false"
    :overlay="false"
    @beforeleave="beforeBack"
  ></page-container>
  <!-- #endif -->
</template>

<script>
export default {
  props: {
    content: {
      type: String,
      default: '确定返回吗?'
    },
    title: {
      type: String,
      default: '系统提示?'
    }
  },
  data() {
    return {
      showPageContainer: true,
      quitFlag: true
    }
  },
  created() {
    // #ifndef MP-WEIXIN
    uni.addInterceptor('navigateBack', {
      invoke: () => {
        if (this.quitFlag) {
          uni.showModal({
            title: this.title,
            content: this.content,
            showCancel: true,
            success: ({ confirm }) => {
              if (confirm) {
                this.quitFlag = false
                this.$emit('backConfirm')
                uni.navigateBack({ delta: 1 })
                return false
              } else {
                this.$emit('backCancel')
              }
            }
          })
          return false
        }
      },
      complete: () => {
        // 删除拦截器
        uni.removeInterceptor('navigateBack')
      }
    })
    // #endif
  },
  methods: {
    beforeBack() {
      this.showPageContainer = false // 必须先隐藏page-container
      uni.showModal({
        title: this.title,
        content: this.content,
        showCancel: true,
        success: ({ confirm }) => {
          if (confirm) {
            this.$emit('backConfirm')
            uni.navigateBack({ delta: 1 })
          } else {
            this.$emit('backCancel')
            this.showPageContainer = true
          }
        }
      })
    }
  }
}
</script>

<style></style>
举报

相关推荐

0 条评论