alertdialog 自定义样式回调选手_Vue.js自定义弹层组件|vue仿微信/ios弹窗

0c3b0be68c03e14de9658c4ce62f262e.gif

最近趁着国庆假期给自己充充电,一直在捣鼓Nuxt.js项目,由于项目中需要用到定制化弹窗功能,本来是想着使用Vant组件库,经过再三考虑,最后决定还是自己重新造一个,于是就有了Vue自定义弹出层VPopup。

aa6e468c6ff060626e02bb6acd2ecf47.png

vpopup 汇合了有赞Vant、京东NutUI等Vue组件库中的 Msg信息框、Popup弹层、Dialog对话框、Toast提示框、ActionSheet动作面板框、Notify通知框 等功能。

3d2c82dc0fafaf18b9f986efe86e8197.png

快速开始

在main.js中引入组件
// 引入弹窗Popupimport Popup from './components/popup';Vue.use(Popup);
vpopup支持标签式函数式两种调用方式。
  • 标签式调用

    <view id="demo">        ...                        <v-popup             v-model="showPopup"             anim="fadeIn"             title="标题内容"            content="弹窗内容,描述文字尽量控制在三行内!"             shadeClose="false"             xclose            :btns="[                {...},                {...},            ]"        />    view>template>
  • 函数式调用

<script>    export default {        ...        methods: {            handleShowPopup() {                let $el = this.$vpopup({                    title: '标题内容',                    content: '弹窗内容,描述文字尽量控制在三行内!',                    anim: 'fadeIn',                    shadeClose: false,                    xclose: true,                    onClose: () => {                        console.log('vpopup is closed!')                    },                    btns: [                        {text: '取消'},                        {                            text: '确定',                            style: 'color:#00a0f1',                            click: () => {                                $el.close()                            }                        }                    ]                });            }        }    }script>

13318d0c45cccbed3663e1a5add07ece.png

两种调用方式均 可,大家可根据实际 项目中的 需求,自行选择任意一种 使用。
  • Msg信息框

264d0c00011a4a8538252a59452fe90f.png

df39e557938cb03f43ddc048f35d34e8.png

f7e673b06c3890807478e009ebde9518.png

<v-popup v-model="showMsg" anim="fadeIn" content="msg提示框测试(3s后窗口关闭)" shadeClose="false" time="3" /><v-popup v-model="showMsgBg" anim="footer" content="自定义背景颜色" shade="false" time="3"     popup-style="background:rgba(0,0,0,.6);color:#fff;"/><v-popup v-model="showConfirm" shadeClose="false" title="警告信息" xclose z-index="2001"    content="
确认框(这里是确认框提示信息)
" :btns="[ {text: '取消', click: () => showConfirm=false}, {text: '确定', style: 'color:#e63d23;', click: handleInfo}, ]"/>
  • IOS弹窗效果

c5e32eead084164a14e9e4952dfa4eb8.png

906d4f51f9ce7561c90b8ce44d1690fe.png

<v-popup v-model="showIos1" type="ios" shadeClose="false" title="标题内容" z-index="1001"  content="弹窗内容,描述文字尽量控制在三行内"  :btns="[    {text: '知道了', click: () => showIos1=false},    {text: '确定', style: 'color:#00e0a1;', click: handleInfo},  ]">v-popup>
  • Toast轻提示框

6f93348ab492247f4df354b7dc90a32f.png

169922e4e5b725eae985e000f49f2521.png

<v-popup v-model="showToast" type="toast" icon="loading" time="2" content="加载中..." /><v-popup v-model="showToast" type="toast" icon="success" shade="false" time="2" content="成功提示" /><v-popup v-model="showToast" type="toast" icon="fail" shade="false" time="2" content="失败提示" />
  • ActionSheet底部面板框

f964065c258c42d9e1f2b03c4b41c6a6.png

a8eb391ccd57f105126e33238019241a.png

65544f2fae2c11cef453093551bb9515.png

<v-popup v-model="showFooter" anim="footer" type="footer" :shadeClose="false" z-index="1001"    content="确定删除该条数据吗?删除后可在7天之内恢复数据,超过7天后数据就无法恢复啦!"    :btns="[        {text: '恢复', style: 'color:#00e0a1;', click: handleInfo},        {text: '删除', style: 'color:#ee0a24;', click: () => null},        {text: '取消', style: 'color:#a9a9a9;', click: () => showFooter=false},    ]"/><v-popup v-model="showActionPicker" anim="footer" type="actionsheetPicker" round title="标题内容"    :btns="[        {text: '取消', click: () => showActionPicker=false},        {text: '确定', style: 'color:#00e0a1;', click: () => null},    ]">        <ul class="goods-list" style="padding:50px;text-align:center;">        <li>双肩包li>        <li>鞋子li>        <li>运动裤li>    ul>v-popup>

okey,这里不一一贴示例代码了。往下看具体实现过程哈~~

实现方式

参数配置:

@@Props------------------------------------------v-model     当前组件是否显示title       标题content     内容(支持自定义插槽内容)type        弹窗类型(toast | footer | actionsheet | actionsheetPicker | android/ios)popupStyle  自定义弹窗样式icon        toast图标(loading | success | fail)shade       是否显示遮罩层shadeClose  是否点击遮罩时关闭弹窗opacity     遮罩层透明度round       是否显示圆角xclose      是否显示关闭图标xposition   关闭图标位置(left | right | top | bottom)xcolor      关闭图标颜色anim        弹窗动画(scaleIn | fadeIn | footer | fadeInUp | fadeInDown)position    弹出位置(top | right | bottom | left)follow      长按/右键弹窗(坐标点)time        弹窗自动关闭秒数(1、2、3)zIndex      弹窗层叠(默认8080)btns        弹窗按钮(参数:text|style|disabled|click) @@$emit------------------------------------------open        打开弹出层时触发(@open="xxx")close       关闭弹出层时触发(@close="xxx") @@Event------------------------------------------onOpen      打开弹窗回调onClose     关闭弹窗回调

弹窗模板:

  
"opened" class="nuxt__popup" :class="{'nuxt__popup-closed': closeCls}" :id="id">
if="JSON.parse(shade)" class="nuxt__overlay" @click="shadeClicked" :style="{opacity}">
class="nuxt__wrap">
class="nuxt__wrap-section">
class="nuxt__wrap-child" :class="['anim-'+anim, type&&'popui__'+type, round&&'round', position]" :style="popupStyle">
if="title" class="nuxt__wrap-tit" v-html="title">
if="type=='toast'&&icon" class="nuxt__toast-icon" :class="['nuxt__toast-'+icon]" v-html="toastIcon[icon]">
if="$slots.content">
class="nuxt__wrap-cnt">"content" />
else>
if="content" class="nuxt__wrap-cnt" v-html="content">
if="btns" class="nuxt__wrap-btns"> for="(btn,index) in btns" :key="index" class="btn" :style="btn.style" v-html="btn.text">
if="xclose" class="nuxt__xclose" :class="xposition" :style="{'color': xcolor}" @click="close">
/** * @Desc     VueJs自定义弹窗组件VPopup * @Time     andy by 2020-10-06 */  let $index = 0, $lockCount = 0, $timer = {};  export default {    props: {      ...    },    data() {      return {        opened: false,        closeCls: '',        toastIcon: {          ...        }      }    },    watch: {      value(val) {        const type = val ? 'open' : 'close';        this[type]();      },    },    methods: {      // 打开弹窗      open() {        if(this.opened) return;        this.opened = true;        this.$emit('open');        typeof this.onOpen === 'function' && this.onOpen();                if(JSON.parse(this.shade)) {          if(!$lockCount) {            document.body.classList.add('nt-overflow-hidden');          }          $lockCount++;        }                // 倒计时关闭        if(this.time) {          $index++;          if($timer[$index] !== null) clearTimeout($timer[$index])          $timer[$index] = setTimeout(() => {            this.close();          }, parseInt(this.time) * 1000);        }                if(this.follow) {          this.$nextTick(() => {            let obj = this.$el.querySelector('.nuxt__wrap-child');            let oW, oH, winW, winH, pos;             oW = obj.clientWidth;            oH = obj.clientHeight;            winW = window.innerWidth;            winH = window.innerHeight;            pos = this.getPos(this.follow[0], this.follow[1], oW, oH, winW, winH);             obj.style.left = pos[0] + 'px';            obj.style.top = pos[1] + 'px';          });        }      },      // 关闭弹窗      close() {        if(!this.opened) return;                this.closeCls = true;        setTimeout(() => {          this.opened = false;          this.closeCls = false;          if(JSON.parse(this.shade)) {            $lockCount--;            if(!$lockCount) {              document.body.classList.remove('nt-overflow-hidden');            }          }          if(this.time) {            $index--;          }          this.$emit('input', false);          this.$emit('close');          typeof this.onClose === 'function' && this.onClose();        }, 200);      },      shadeClicked() {        if(JSON.parse(this.shadeClose)) {          this.close();        }      },      btnClicked(e, index) {        let btn = this.btns[index];        if(!btn.disabled) {          typeof btn.click === 'function' && btn.click(e)        }      },      getZIndex() {        for(var $idx = parseInt(this.zIndex), $el = document.getElementsByTagName('*'), i = 0, len = $el.length; i < len; i++)          $idx = Math.max($idx, $el[i].style.zIndex)        return $idx;      },      // 获取弹窗坐标点      getPos(x, y, ow, oh, winW, winH) {        let l = (x + ow) > winW ? x - ow : x;        let t = (y + oh) > winH ? y - oh : y;        return [l, t];      }    },  }

组件通过监听传过来的 v-model 值来调用openclose方法。

watch: {    value(val) {        const type = val ? 'open' : 'close';        this[type]();    },},
另外还支持 右键/长按弹窗 , 自定义slot插槽 内容。

6cfee025ff55e01d2ad2e9e9cee4dd16.png

c2dfe7f3a80040a71a3a910faffe090d.png

ce9e9f72f24def22afbf68e80566b065.png

<v-popup v-model="showContextMenu2" type="contextmenu" :follow="followPos" opacity="0"    :btns="[        {text: '标为未读', click: handleContextPopup},        {text: '消息免打扰'},        {text: '置顶聊天'},        {text: '删除', click: () => showContextMenu2=false},    ]"/>

函数式调用

组件通过 Vue.extend 扩展实例构造器来实现函数式调用方式。
import Vue from 'vue';import VuePopup from './popup.vue';let PopupConstructor = Vue.extend(VuePopup);let $instance;let VPopup = function(options = {}) {    // 同一个页面中,id相同的Popup的DOM只会存在一个    options.id = options.id || 'nuxt-popup-id';    $instance = new PopupConstructor({        propsData: options    });    $instance.vm = $instance.$mount();    let popupDom = document.querySelector('#' + options.id);    if(options.id && popupDom) {        popupDom.parentNode.replaceChild($instance.$el, popupDom);    } else {        document.body.appendChild($instance.$el);    }    Vue.nextTick(() => {        $instance.value = true;    })    return $instance;}VPopup.install = () => {    Vue.prototype['$vpopup'] = VPopup;    Vue.component('v-popup', VuePopup);}export default VPopup;

通过如上方法就实现了把 $vpopup 方法挂载到Vue原型上并注册 v-popup 组件。

就可以愉快的使用 this.$vpopup({...}) 函数来进行调用。

dedeeb1ba367c67cf40dc221d6459049.gif

好了,基于Vue开发自定义弹窗就介绍到这里。希望对大家有所帮助!

969f7b1b7515bb857e1ef2c331db94e8.gif

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,我可以为您介绍一下Android仿IOS定义AlertDialog提示框的实现方法。 首先,我们需要在Android项目中创建一个自定义布局文件,用于显示框的内容。可以使用LinearLayout或RelativeLayout等布局容器来组织框的内容,例如: ```xml <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="vertical"> <TextView android:id="@+id/title" android:layout_width="match_parent" android:layout_height="wrap_content" android:gravity="center" android:text="标题" android:textSize="18sp" /> <TextView android:id="@+id/message" android:layout_width="match_parent" android:layout_height="wrap_content" android:gravity="center" android:text="内容" android:textSize="14sp" /> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="horizontal" android:gravity="center"> <Button android:id="@+id/confirm" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="确定" /> <Button android:id="@+id/cancel" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="取消" /> </LinearLayout> </LinearLayout> ``` 接下来,我们需要创建一个自定义AlertDialog类,用于显示框和处理按钮点击事件。在这个类中,我们需要实现onCreateDialog方法来加载自定义布局文件,并设置框的标题、内容和按钮监听器等。例如: ```java public class IOSAlertDialog extends DialogFragment { private String title; private String message; private DialogInterface.OnClickListener confirmListener; private DialogInterface.OnClickListener cancelListener; public IOSAlertDialog(String title, String message, DialogInterface.OnClickListener confirmListener, DialogInterface.OnClickListener cancelListener) { this.title = title; this.message = message; this.confirmListener = confirmListener; this.cancelListener = cancelListener; } @Override public Dialog onCreateDialog(Bundle savedInstanceState) { LayoutInflater inflater = LayoutInflater.from(getActivity()); View view = inflater.inflate(R.layout.dialog_ios_alert, null); TextView titleView = view.findViewById(R.id.title); TextView messageView = view.findViewById(R.id.message); Button confirmButton = view.findViewById(R.id.confirm); Button cancelButton = view.findViewById(R.id.cancel); titleView.setText(title); messageView.setText(message); confirmButton.setOnClickListener(confirmListener); cancelButton.setOnClickListener(cancelListener); AlertDialog.Builder builder = new AlertDialog.Builder(getActivity()); builder.setView(view); return builder.create(); } } ``` 最后,在我们的Activity中,我们可以通过创建一个实例对象,并用show方法来显示框。例如: ```java IOSAlertDialog dialog = new IOSAlertDialog( "提示", "确定要删除吗?", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { // 确定按钮点击事件 } }, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { // 取消按钮点击事件 } }); dialog.show(getSupportFragmentManager(), "IOSAlertDialog"); ``` 这样,我们就可以实现一个Android仿IOS定义AlertDialog提示框了。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值