likes
comments
collection
share

小程序 van-dialog确认时阻止弹窗关闭

作者站长头像
站长
· 阅读数 117

前言

最近项目小程序中做了一个修改物流的功能,利用van-dialog实现了弹窗,但是点击确定的前提前需要进行一次表单校验,这时表单校验为失败,但是弹窗被关闭了,因此我将调试的解决方法记录在此

解决步骤:

-   利用api的`beforeClose` 实现确认时不关闭弹窗
-   表单校验成功时,利用变量关闭弹窗

利用api的beforeClose 实现确认时不关闭弹窗

注意点:

  • beforeClosePromise或者boolean类型
  • van-dialog的 默认z-index 为100,比toast大,因此将dialog的z-index改为10

主要代码如下

<template>  
<van-dialog
      class="logistics-dialog"
      z-index="10"
      use-slot
      show="{{ show }}"
      show-cancel-button
      bind:confirm="saveLogistics"
      before-close="{{beforeClose}}"
      bind:close="closeDialog"
    >
      <view style="margin:48rpx 0; padding: 0 24rpx">
        <van-field
          required
          is-link
          bindtap="openType"
          value="{{shipperName}}"
          placeholder="请选择物流公司"
        ></van-field>
        <van-field
          required
          value="{{logisticsCode}}"
          placeholder="请输入物流单号"
          bind:change="changeLogisticsCode"
        ></van-field>
      </view>
    </van-dialog>
</template>
<script>
  export default class Factory extends wepy.page {
    data = {
      beforeClose: {},
      show: false,
      postTypeShow: false,
      postTypeArr: [],
      logisticsCode: '',
      shipperName: '',
      shipperCode: '',
    }
  
    onLoad() {
    this.beforeClose = (action) => new Promise((resolve) => {
      setTimeout(() => {
        if (action === 'confirm') {
          // 拦截确认操作
          resolve(false);
        } else {
          resolve(true);
        }
      }, 0);
    });
  };
  }
</script>

表单校验成功时,手动调用关闭弹窗方法

代码如下

    closeDialog() {
      this.show = false;
      this.postTypeShow = false;
      this.shipperCode = '';
      this.shipperName = '';
      this.logisticsCode = '';
      this.orderInfoId = [];
    },
     saveLogistics() {
      // 校验
      if (!this.shipperCode) {
        Toast.fail('请选择物流公司');
      } else if (!this.logisticsCode) {
        Toast.fail('请输入物流单号');
      } else {
        let param = {
          logisticsCode: this.logisticsCode,
          orderInfoId: this.orderInfoId,
          shipperCode: this.shipperCode
        }
        saveLogisticsCode(param).then(res => {
          if (res.code === 200) {
            Toast.success('修改物流单号成功');
            this.getManufactorOrder(true);
          }
         this.closeDialog() ;
        })
      }
    },

效果如下

小程序 van-dialog确认时阻止弹窗关闭

转载自:https://juejin.cn/post/7008080619624202270
评论
请登录