站长图库向大家介绍了uni-app,全局弹层组件,代码示例等相关知识,希望对您有所帮助
uni-app中怎么开发一个全局弹层组件?下面本篇文章给大家通过例子介绍一下uni-app中实现一个全局弹层组件的方法,希望对大家有所帮助!

公司有一个采用uni-app框架写的app应用,里面的弹层基本是使用官方的uni.showModal之类的api实现弹层,在设备上表现就是原生的弹层,在客户的要求下,需要更换成设计的样式,所以就开始实现这样一个组件。
根据弹层经常使用的方法和方式可以大致列出他需要的属性和方法:
类型:
alert/confirm等展示图标 icon
展示内容 content
可以api调用
支持
promise,可以使用$api.xx().then
前几项就很好做,就在data中定义好字段,外层直接拿官方的轮子uni-popup,这样少写一些控制弹出的逻辑(懒的),这样大致结构就写好了
// template部分<uni-popup ref="popup" :maskClick="maskClick"> <view class="st-layer" :style="{ width: width }"> <view class="st-layer__content"> <!-- #ifndef APP-NVUE --> <text class="st-layer__icon" :class="option.iconClass || getIconClass()" v-if="option.type !== 'none' && option.showIcon"></text> <!-- #endif --> <view class="st-layer__msg" v-if="option.msg"> <text>{{ option.msg }}</text> </view> </view> <view class="st-layer__footer" :class="{'is-reverse-cofirmcancel' : isReverseConfirmCancel}" v-if="option.showConfirmButton || option.showCancelButton"> <view class="st-layer__footer__btn st-layer__footer__btn--confirm" @tap.stop="confirmClick" v-if="option.showConfirmButton"><text>确认</text></view> <view class="st-layer__footer__btn st-layer__footer__btn--cancel" @tap.stop="cancelClick" v-if="option.showCancelButton"><text>取消</text></view> </view> </view></uni-popup>然后js部分先简单实现了一些open和close方法
data() { return { option: {} }},methods: { open(option) { let defaultOption = { showCancelButton: false, // 是否显示取消按钮 cancelButtonText: '取消', // 取消按钮文字 showConfirmButton: true, // 是否显示确认按钮 confirmButtonText: '取消', // 确认按钮文字 showIcon: true, // 是否显示图标 iconClass: null, // 图标class自定义 type: 'none', // 类型 confirm: null, // 点击确认后的逻辑 cancel: null, // 点击取消后的逻辑 msg: '' } this.option = Object.assign({}, defaultOption, option) this.$refs.popup.open() }, close() { this.$refs.popup.close() }, confirmClick() { const confirmHandler = this.option.confirm if (confirmHandler && typeof confirmHandler === 'function') { confirmHandler() } this.close() this.$emit('confirm') }, cancelClick() { const cancelHandler = this.option.cancel if (cancelHandler && typeof cancelHandler === 'function') { cancelHandler() } this.close() this.$emit('cancel') }}目前在其他页面已经可以使用
// test.vue 可以使用uni-app的 [easycom组件规范](https://uniapp.dcloud.io/component/README?id=easycom%e7%bb%84%e4%bb%b6%e8%a7%84%e8%8c%83),不用写import语句<st-layer ref="stLayer"></st-layer>
// js部分this.$refs.stLayer.open({ msg: '测试', confirm: () => {  

