关于vue3:vue30自定义弹窗组件vue3-pc端对话框vue3layer

102次阅读

共计 8940 个字符,预计需要花费 23 分钟才能阅读完成。

介绍

Vue3-Layer 一款基于 vue3.x 实现的 PC 桌面端弹窗组件。领有极简的调用形式、超多的参数配置。反对拖拽、缩放、最大化、全局、自定义弹窗款式等性能。


疾速引入

// 在 main.js 中全局引入组件
import {createApp} from 'vue'
import App from './App.vue'

const app = createApp(App)

// 引入 Element-Plus 组件库
import ElementPlus from 'element-plus'
import 'element-plus/lib/theme-chalk/index.css'

// 引入弹窗组件 v3layer
import Vue3Layer from './components/v3layer'

app.use(ElementPlus)
app.use(Vue3Layer)

app.mount('#app')

v3layer 同样反对标签式 + 函数式两种调用形式。

  • 标签式调用
<v3-layer 
    v-model="showDialog"
    title="题目内容"
    content="<div style='color:#f57b16;padding:30px;'> 这里是内容信息!</div>"
    z-index="1011"
    lockScroll="false"
    xclose
    resize
    dragOut
    :btns="[{text: '勾销', click: () => showDialog=false},
        {text: '确认', style: 'color:#f90;', click: handleSure},
    ]"
/>
    <template v-slot:content> 这里是自定义插槽内容信息!</template>
</v3-layer>
  • 函数式调用
let $el = v3layer({
    title: '题目内容',
    content: '<div style='color:#f57b16;padding:30px;'> 这里是内容信息!</div>', 
    shadeClose: false,
    zIndex: 1011,
    lockScroll: false,
    xclose: true,
    resize: true,
    dragOut: true,
    btns: [{text: '勾销', click: () => {$el.close() }},
        {text: '确认', click: () => handleSure},
    ]
});

当弹窗类型为 message | popover | notify 则调用如下:

v3layer.message({...})
v3layer.notify({...})
v3layer.popover({...})

传入自定义参数即可实现上述弹窗类型成果。


Vue3.0 中提供了两种全局挂载形式 app.config.globalPropertiesapp.provide 具体应用能够去参看官网阐明。
https://v3.cn.vuejs.org/api/a…
https://v3.cn.vuejs.org/guide…
另外应用的话,在这一篇文章也有些介绍。
https://segmentfault.com/a/11…








实现过程

在 components 目录下新建 v3layer 文件。

  • v3layer 配置参数
|props 参数 |
v-model         是否显示弹框
id              弹窗惟一标识
title           题目
content         内容(反对 String、带标签内容、自定义插槽内容)*** 如果 content 内容比较复杂,举荐应用标签式写法
type            弹框类型(toast|footer|actionsheet|actionsheetPicker|android|ios|contextmenu|drawer|iframe)layerStyle      自定义弹窗款式
icon            toast 图标(loading | success | fail)shade           是否显示遮罩层
shadeClose      是否点击遮罩时敞开弹窗
lockScroll      是否弹窗呈现时将 body 滚动锁定
opacity         遮罩层透明度
xclose          是否显示敞开图标
xposition       敞开图标地位(left | right | top | bottom)xcolor          敞开图标色彩
anim            弹窗动画(scaleIn | fadeIn | footer | fadeInUp | fadeInDown | fadeInLeft | fadeInRight)position        弹出地位(auto | ['100px','50px'] | t | r | b | l | lt | rt | lb | rb)drawer          抽屉弹窗(top | right | bottom | left)follow          追随元素定位弹窗(反对元素.kk #kk 或 [e.clientX, e.clientY])time            弹窗主动敞开秒数(1、2、3)zIndex          弹窗层叠(默认 8080)teleport        指定挂载节点(默认是挂载组件标签地位,可通过 teleport 自定义挂载地位)teleport="body | #xxx | .xxx"
topmost         置顶以后窗口(默认 false)area            弹窗宽高(默认 auto)设置宽度 area: '300px' 设置高度 area:['','200px'] 设置宽高 area:['350px','150px']
maxWidth        弹窗最大宽度(只有当 area:'auto' 时,maxWidth 的设定才无效)maximize        是否显示最大化按钮(默认 false)fullscreen      全屏弹窗(默认 false)fixed           弹窗是否固定
drag            拖拽元素(可定义选择器 drag:'.xxx' | 禁止拖拽 drag:false)dragOut         是否容许拖拽到窗口外(默认 false)lockAxis        限度拖拽方向可选: v 垂直、h 程度,默认不限度
resize          是否容许拉伸尺寸(默认 false)btns            弹窗按钮(参数:text|style|disabled|click)++++++++++++++++++++++++++++++++++++++++++++++
|emit 事件触发 |
success         层弹出后回调(@success="xxx")end             层销毁后回调(@end="xxx")++++++++++++++++++++++++++++++++++++++++++++++
|event 事件 |
onSuccess       层关上回调事件
onEnd           层敞开回调事件
  • v3layer 模板及逻辑解决
<template>
    <div ref="elRef" v-show="opened" class="vui__layer" :class="{'vui__layer-closed': closeCls}" :id="id">
        <!-- // 蒙版 -->
        <div v-if="JSON.parse(shade)" class="vlayer__overlay" @click="shadeClicked" :style="{opacity}"></div>
        <div class="vlayer__wrap" :class="['anim-'+anim, type&&'popui__'+type, tipArrow]" :style="[layerStyle]">
            <div v-if="title" class="vlayer__wrap-tit" v-html="title"></div>
            <div v-if="type=='toast'&&icon" class="vlayer__toast-icon" :class="['vlayer__toast-'+icon]" v-html="toastIcon[icon]"></div>
            <div class="vlayer__wrap-cntbox">
                <!-- 判断插槽是否存在 -->
                <template v-if="$slots.content">
                    <div class="vlayer__wrap-cnt"><slot name="content" /></div>
                </template>
                <template v-else>
                    <template v-if="content">
                        <iframe v-if="type=='iframe'"scrolling="auto"allowtransparency="true"frameborder="0":src="content"></iframe>
                        <!-- message|notify|popover -->
                        <div v-else-if="type=='message'|| type=='notify'|| type=='popover'"class="vlayer__wrap-cnt">
                            <i v-if="icon" class="vlayer-msg__icon" :class="icon" v-html="messageIcon[icon]"></i>
                            <div class="vlayer-msg__group"><div v-if="title" class="vlayer-msg__title" v-html="title"></div><div v-html="content"></div></div>
                        </div>
                        <div v-else class="vlayer__wrap-cnt" v-html="content"></div>
                    </template>
                </template>
                <slot />
            </div>
            <div v-if="btns" class="vlayer__wrap-btns">
                <span v-for="(btn,index) in btns" :key="index" class="btn" :style="btn.style" @click="btnClicked($event,index)" v-html="btn.text"></span>
            </div>
            <span v-if="xclose" class="vlayer__xclose" :class="!maximize&&xposition" :style="{'color': xcolor}" @click="close"></span>
            <span v-if="maximize" class="vlayer__maximize" @click="maximizeClicked($event)"></span>
            <span v-if="resize" class="vlayer__resize"></span>
        </div>
        <!-- 优化拖拽卡顿 -->
        <div class="vlayer__dragfix"></div>
    </div>
</template>
/**
 * @Desc     Vue3.0 桌面端弹窗组件 V3Layer
 * @Time     andy by 2021-1
 * @About    Q:282310962  wx:xy190310
 */
<script>
    import {onMounted, onUnmounted, ref, reactive, watch, toRefs, nextTick} from 'vue'
    import domUtils from './utils/dom.js'
    // 索引,蒙层管制,定时器
    let $index = 0, $locknum = 0, $timer = {}, $closeTimer = null
    export default {
        props: {// ...},
        emits: ['update:modelValue'],
        setup(props, context) {const elRef = ref(null);

            const data = reactive({
                opened: false,
                closeCls: '',
                toastIcon: {// ...},
                messageIcon: {// ...},
                vlayerOpts: {},
                tipArrow: null,
            })

            onMounted(() => {if(props.modelValue) {open();
                }
                window.addEventListener('resize', autopos, false);
            })

            onUnmounted(() => {window.removeEventListener('resize', autopos, false);
                clearTimeout($closeTimer);
            })

            // 监听弹层 v -model
            watch(() => props.modelValue, (val) => {// console.log('V3Layer is now [%s]', val ? 'show' : 'hide')
                if(val) {open();
                }else {close();
                }
            })

            // 关上弹窗
            const open = () => {if(data.opened) return;
                data.opened = true;
                typeof props.onSuccess === 'function' && props.onSuccess();

                const dom = elRef.value;
                // 弹层挂载地位
                if(props.teleport) {nextTick(() => {let teleportNode = document.querySelector(props.teleport);
                        teleportNode.appendChild(dom);

                        auto();})
                }

                callback();}

            // 敞开弹窗
            const close = () => {if(!data.opened) return;

                let dom = elRef.value;
                let vlayero = dom.querySelector('.vlayer__wrap');
                let ocnt = dom.querySelector('.vlayer__wrap-cntbox');
                let omax = dom.querySelector('.vlayer__maximize');

                data.closeCls = true;
                clearTimeout($closeTimer);
                $closeTimer = setTimeout(() => {
                    data.opened = false;
                    data.closeCls = false;
                    if(data.vlayerOpts.lockScroll) {
                        $locknum--;
                        if(!$locknum) {
                            document.body.style.paddingRight = '';
                            document.body.classList.remove('vui__body-hidden');
                        }
                    }
                    if(props.time) {$index--;}
                    // 革除弹窗款式
                    vlayero.style.width = vlayero.style.height = vlayero.style.top = vlayero.style.left = '';
                    ocnt.style.height = '';
                    omax && omax.classList.contains('maximized') && omax.classList.remove('maximized');
                    
                    data.vlayerOpts.isBodyOverflow && (document.body.style.overflow = '');

                    context.emit('update:modelValue', false);
                    typeof props.onEnd === 'function' && props.onEnd();}, 200)
            }

            // 弹窗地位
            const auto = () => {
                // ...

                autopos();

                // 全屏弹窗
                if(props.fullscreen) {full();
                }

                // 弹窗拖动 | 缩放
                move();}

            const autopos = () => {if(!data.opened) return;
                let oL, oT
                let pos = props.position;
                let isFixed = JSON.parse(props.fixed);
                let dom = elRef.value;
                let vlayero = dom.querySelector('.vlayer__wrap');

                if(!isFixed || props.follow) {vlayero.style.position = 'absolute';}
                
                let area = [domUtils.client('width'), domUtils.client('height'), vlayero.offsetWidth, vlayero.offsetHeight]
                
                oL = (area[0] - area[2]) / 2;
                oT = (area[1] - area[3]) / 2;

                if(props.follow) {offset();
                }else {
                    typeof pos === 'object' ? (oL = parseFloat(pos[0]) || 0, oT = parseFloat(pos[1]) || 0
                    ) : (
                        pos == 't' ? oT = 0 : 
                        pos == 'r' ? oL = area[0] - area[2] : 
                        pos == 'b' ? oT = area[1] - area[3] : 
                        pos == 'l' ? oL = 0 : 
                        pos == 'lt' ? (oL = 0, oT = 0) : 
                        pos == 'rt' ? (oL = area[0] - area[2], oT = 0) : 
                        pos == 'lb' ? (oL = 0, oT = area[1] - area[3]) :
                        pos == 'rb' ? (oL = area[0] - area[2], oT = area[1] - area[3]) : 
                        null
                    )

                    vlayero.style.left = parseFloat(isFixed ? oL : domUtils.scroll('left') + oL) + 'px';
                    vlayero.style.top = parseFloat(isFixed ? oT : domUtils.scroll('top') + oT) + 'px';
                }
            }

            // 元素追随定位
            const offset = () => {
                let oW, oH, pS
                let dom = elRef.value
                let vlayero = dom.querySelector('.vlayer__wrap');

                oW = vlayero.offsetWidth;
                oH = vlayero.offsetHeight;
                pS = domUtils.getFollowRect(props.follow, oW, oH);
                data.tipArrow = pS[2];
                
                vlayero.style.left = pS[0] + 'px';
                vlayero.style.top = pS[1] + 'px';
            }

            // 最大化弹窗
            const full = () => {// ...}

            // 复原弹窗
            const restore = () => {
                let dom = elRef.value;
                let vlayero = dom.querySelector('.vlayer__wrap');
                let otit = dom.querySelector('.vlayer__wrap-tit');
                let ocnt = dom.querySelector('.vlayer__wrap-cntbox');
                let obtn = dom.querySelector('.vlayer__wrap-btns');
                let omax = dom.querySelector('.vlayer__maximize');

                let t = otit ? otit.offsetHeight : 0
                let b = obtn ? obtn.offsetHeight : 0

                if(!data.vlayerOpts.lockScroll) {
                    data.vlayerOpts.isBodyOverflow = false;
                    document.body.style.overflow = '';
                }
                
                props.maximize && omax.classList.remove('maximized')
                
                vlayero.style.left = parseFloat(data.vlayerOpts.rect[0]) + 'px';
                vlayero.style.top = parseFloat(data.vlayerOpts.rect[1]) + 'px';
                vlayero.style.width = parseFloat(data.vlayerOpts.rect[2]) + 'px';
                vlayero.style.height = parseFloat(data.vlayerOpts.rect[3]) + 'px';
            }

            // 拖动 | 缩放弹窗
            const move = () => {// ...}

            // 事件处理
            const callback = () => {
                // 倒计时敞开
                if(props.time) {
                    $index++
                    // 避免反复点击
                    if($timer[$index] !== null) clearTimeout($timer[$index])
                    $timer[$index] = setTimeout(() => {close();
                    }, parseInt(props.time) * 1000)
                }
            }

            // 点击最大化按钮
            const maximizeClicked = (e) => {
                let o = e.target
                if(o.classList.contains('maximized')) {
                    // 复原
                    restore();} else {
                    // 最大化
                    full();}
            }
            // 点击遮罩层
            const shadeClicked = () => {if(JSON.parse(props.shadeClose)) {close();
                }
            }
            // 按钮事件
            const btnClicked = (e, index) => {let btn = props.btns[index]
                if(!btn.disabled) {typeof btn.click === 'function' && btn.click(e)
                }
            }
            
            return {...toRefs(data),
                elRef,
                close,
                maximizeClicked,
                shadeClicked,
                btnClicked,
            }
        }
    }
</script>

大家能够在此基础上裁减一些想要的成果。
vue3.0 中把弹框实例挂载到 body 上可通过 createAppcreateVNode实现。大家感兴趣也能够看看之前分享的一篇文章。

ok,应用 Vue3 开发自定义 alert/dialog 组件就分享到这里。感激大家的浏览!✍

正文完
 0