微信小程序实现监听点击返回挽留弹框功能(支持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>

相关推荐

  1. uniapp程序保存图片

    2024-03-29 07:02:03       68 阅读
  2. 程序实现各类、自定义

    2024-03-29 07:02:03       64 阅读

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-03-29 07:02:03       94 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-03-29 07:02:03       101 阅读
  3. 在Django里面运行非项目文件

    2024-03-29 07:02:03       82 阅读
  4. Python语言-面向对象

    2024-03-29 07:02:03       91 阅读

热门阅读

  1. 了解机器学习/深度学习常用的框架、工具

    2024-03-29 07:02:03       42 阅读
  2. Python手册(Machine Learning)--XGBoost

    2024-03-29 07:02:03       42 阅读
  3. 双指针算法篇:两数之和 、三数之和

    2024-03-29 07:02:03       40 阅读
  4. React + 项目(从基础到实战) -- 第一期

    2024-03-29 07:02:03       48 阅读
  5. 总结网络中的一些基本概念

    2024-03-29 07:02:03       43 阅读
  6. EasyExcel模板填充以及填充多个sheet

    2024-03-29 07:02:03       35 阅读
  7. mac上查看以及修改DNS配置

    2024-03-29 07:02:03       44 阅读
  8. Composer常见错误解决

    2024-03-29 07:02:03       37 阅读
  9. 【云开发笔记No.7】敏捷开发

    2024-03-29 07:02:03       49 阅读