封装uniapp全局弹窗并绑定到原型上

调用方式

// main.js中引入
import './popup'
// Toast
// 1、带成功图标提示框
this.$Toast('success', '提交成功!', () => {
	// 提示框关闭后
})
// 2、不带任何图标提示框
this.$Toast('none', '请输入手机号', () => {
	// 提示框关闭后
})
// 3、带loading图标提示框
this.$Toast('loading', '加载中…')

// Confirm
this.$Confirm(
  '提示',
  '确认保存到相册吗?',
  '保存',
  () => {
    // 点击确认
  },
  '取消',
  () => {
    // 点击取消
  }
)

// Alert
this.$Alert(
  '提示',
  '操作成功!',
  '我知道了',
  () => {
    // 点击确认
  }
)

相较于原生的调用方式,是不是更加简洁了呢?
来看看是怎么实现的

新建popup.js

// 如果uniapp中
import Vue from 'vue'
// 如果是小程序中(待编写)
// Toast
// icon、title为必传
const Toast = (icon, title, onShow = null, duration = 1800, mask) => {
  // loading框
  if (icon === 'loading') {
    uni.showLoading({ title })
    // 关闭Loading调用
		// uni.hideLoading()
  } else {
    uni.showToast({
      title, // 提示的内容,
      icon, // 图标,
      duration, // 延迟时间,
      mask, // 显示透明蒙层,防止触摸穿透,
      success: res => {
        if (onShow) {
          let timer = setTimeout(() => {
            onShow()
            clearTimeout(timer)
          }, duration)
        }
      }
    })
  }
}

// Confirm
// title、content为必传
const Confirm = (title = '提示', content, confirmText = '确定', onConfirm, cancelText = '取消', onCancel = null) => {
  uni.showModal({
    title, // 提示的标题,
    content, // 提示的内容,
    showCancel: true, // 是否显示取消按钮,
    cancelText, // 取消按钮的文字,默认为取消,最多 4 个字符(注:多了弹窗不会显示),
    cancelColor: '#000000', // 取消按钮的文字颜色,
    confirmText, // 确定按钮的文字,默认为取消,最多 4 个字符(注:多了弹窗不会显示),
    confirmColor: '#e7aa3d', // 确定按钮的文字颜色,
    success: res => {
      if (res.confirm) {
        onConfirm()
      } else if (res.cancel) {
        if (onCancel) {
          onCancel()
        }
      }
    }
  })
}

// Alert
// title、content为必传
const Alert = (title = '', content, confirmText = '确定', onConfirm) => {
  uni.showModal({
    title,
    content, // 提示的内容,
    showCancel: false, // 是否显示取消按钮,
    confirmText, // 确定按钮的文字,默认为取消,最多4个字符(注:多了弹窗不会显示),
    confirmColor: '#e7aa3d', // 确定按钮的文字颜色,
    success: res => {
      if (res.confirm && onConfirm) {
        onConfirm()
      }
    }
  })
}

// 注册到Vue原型上
Vue.prototype.$Toast = Toast
Vue.prototype.$Confirm = Confirm
Vue.prototype.$Alert = Alert
  • 0
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值