vue pc端自定义对话框组件|vue.js弹层VLayer

基于Vue实现自定义网页弹窗组件|vue.js pc弹层VLayer

VLayer 最近开发的一款汇集众多功能的Vue轻量级桌面端对话框组件。在设计开发之初借鉴了业界有名的Layer弹窗、Element-UI、iView等组件化设计思想。拥有丰富的参数配置及漂亮的皮肤。

vlayer 集合了Alert、Dialog、Message、Notification、ActionSheet、Toast、Popover、Popconfirm等多种类型弹窗。

vue移动端自定义弹框VPopup组件,可以参看下面这篇。

https://blog.csdn.net/yanxinyun1990/article/details/108951470

使用

// 在main.js中引入组件
import VLayer from './components/vlayer';
Vue.use(VLayer);

vlayer支持标签式函数式两种写法。

  • 标签式调用
<v-layer 
    v-model="isShowDialog"
    title="标题"
    content="<div style='color:#00e0a1;padding:20px;'>显示弹窗内容信息!</div>"
    xclose
    z-index="1001"
    lockScroll="false"
    resize
    dragOut
    :btns="[
        {text: '取消', click: () => isShowDialog=false},
        {text: '确定', style: 'color:#f90;', click: handleFn},
    ]"
/>
  • 函数式调用

vlayer也支持函数式写法  this.$vlayer({...})  另外提供了30+种参数灵活配置。

let $vlayero = this.$vlayer({
    title: '标题',
    content: '<div style='color:#00e0a1;padding:20px;'>显示弹窗内容信息!</div>', 
    xclose: true,
    zIndex: 1001,
    lockScroll: false,
    resize: true,
    dragOut: true,
    btns: [
        {text: '取消', click: () => { $vlayero.close(); }},
        {text: '确定', click: () => this.handleFn()},
    ]
});

效果预览

默认参数配置

支持如下丰富的参数配置,可以灵活搭配出想要的弹框效果。

@@默认参数
v-model     当前组件是否显示
title       标题
content     内容(支持自定义插槽内容)
type        弹窗类型(toast | footer | actionsheet | android/ios | contextmenu | drawer | iframe | message/notify/popover)
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)
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)
resize      是否允许拉伸尺寸(默认false)
btns        弹窗按钮(参数:text|style|disabled|click)
------------------------------------------
@@组件式事件
open        打开弹出层时触发(@open="xxx")
close       关闭弹出层时触发(@close="xxx")
------------------------------------------
@@函数式事件
onOpen      打开弹窗回调
onClose     关闭弹窗回调

弹层模板vlayer.vue

<template>
  <div v-show="opened" class="vui__layer" :class="{'vui__layer-closed': closeCls}" :id="vlayerId">
    <!-- //遮罩 -->
    <div v-if="JSON.parse(shade)" class="vlayer__overlay" @click="shadeClicked" :style="{opacity}"></div>
    <!-- //窗体 -->
    <div class="vlayer__wrap" :class="['anim-'+anim, type&&'popui__'+type, drawer&&'popui__drawer-'+drawer, xclose&&'vlayer-closable', 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 class="vlayer-msg__content" 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" :class="{'btn-disabled': btn.disabled}" :style="btn.style" 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"></span>
      <span v-if="resize" class="vlayer__resize"></span>
    </div>
    <!-- 修复拖拽卡顿 -->
    <div class="vlayer__dragfix"></div>
  </div>
</template>
/**
 * @Desc     vue自定义桌面端弹层组件VLayer
 * @Time     andy by 2020-10-28
 * @About    Q:282310962  wx:xy190310
 */
<script>
  import domUtils from './utils/dom'
  let $index = 0, $lockCount = 0, $timer = {};
  let ie = !!window.ActiveXObject || "ActiveXObject" in window;
  export default {
    props: {
      // ...
    },
    data() {
      return {
        opened: false,
        closeCls: '',
        toastIcon: {
          // ...
        },
        messageIcon: {
          // ...
        },
        vlayerOpts: {},
        tipArrow: null,
      }
    },
    mounted() {
      window.addEventListener('resize', () => {
        this.autopos();
      })
    },
    computed: {
      vlayerId() {
        return this.id ? this.id : `vlayer-${domUtils.generateId()}`;
      }
    },
    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();

        const dom = this.$el;
        this.$nextTick(() => {
          document.body.appendChild(dom);
          
          this.auto();
        })
        
        this.callback();
      },
      // 关闭弹窗
      close() {
        if(!this.opened) return;

        let dom = this.$el;
        let vlayero = dom.querySelector('.vlayer__wrap');
        let ocnt = dom.querySelector('.vlayer__wrap-cntbox');
        let omax = dom.querySelector('.vlayer__maximize');
        
        this.closeCls = true;
        setTimeout(() => {
          this.opened = false;
          this.closeCls = false;
          if(this.vlayerOpts.lockScroll) {
            $lockCount--;
            if(!$lockCount) {
              document.body.style.paddingRight = '';
              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);
      },

      // 弹窗位置
      auto() {
        // ...

        this.autopos();

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

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

      autopos() {
        if(!this.opened) return;
        let oL, oT;
        let pos = this.position;
        let isFixed = JSON.parse(this.fixed);
        let dom = this.$el;
        let vlayero = dom.querySelector('.vlayer__wrap');
        
        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(this.follow) {
          this.offset();
        }else {
          typeof pos === 'object' ? (
            oL = parseFloat(pos[0]) || 0, oT = parseFloat(pos[1]) || 0
          ) : (
            // ...
          )

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

      // 元素跟随定位
      offset() {
        let oW, oH, pS;
        let dom = this.$el;
        let vlayero = dom.querySelector('.vlayer__wrap');

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

      // 最大化弹窗
      full() {
        let timer;
        let isFixed = JSON.parse(this.fixed);
        let dom = this.$el;
        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;

        let rect = [
          parseFloat(domUtils.getStyle(vlayero, 'left')), parseFloat(domUtils.getStyle(vlayero, 'top')),
          parseFloat(domUtils.getStyle(vlayero, 'width')), parseFloat(domUtils.getStyle(vlayero, 'height'))||vlayero.offsetHeight
        ]
        this.vlayerOpts.rect = rect;
        
        clearTimeout(timer);
        timer = setTimeout(() => {
          vlayero.style.left = isFixed ? 0 : domUtils.scroll('left') + 'px';
          vlayero.style.top = isFixed ? 0 : domUtils.scroll('top') + 'px';
          vlayero.style.width = domUtils.client('width') + 'px';
          vlayero.style.height = domUtils.client('height') + 'px';
          ocnt.style.height = domUtils.client('height') - t - b + 'px';
        }, 16);
      },

      // 恢复弹窗
      restore() {
        let dom = this.$el;
        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;
        
        vlayero.style.left = parseFloat(this.vlayerOpts.rect[0]) + 'px';
        vlayero.style.top = parseFloat(this.vlayerOpts.rect[1]) + 'px';
        vlayero.style.width = parseFloat(this.vlayerOpts.rect[2]) + 'px';
        vlayero.style.height = parseFloat(this.vlayerOpts.rect[3]) + 'px';
        ocnt.style.height = parseFloat(this.vlayerOpts.rect[3]) - t - b + 'px';
      },

      // 拖动|缩放弹窗
      move() {
        // ...
      },

      // 事件处理
      callback() {
        // 倒计时关闭
        if(this.time) {
          $index++;
          // 防止重复点击
          if($timer[$index] !== null) clearTimeout($timer[$index])
          $timer[$index] = setTimeout(() => {
            this.close();
          }, parseInt(this.time) * 1000);
        }
      },
      // 点击最大化按钮
      maximizeClicked(e) {
        let o = e.target;
        if(o.classList.contains('maximized')) {
          // 恢复
          this.restore();
        } else {
          // 最大化
          this.full();
        }
      },
      // 点击遮罩层
      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)
        }
      },
    },
  }
</script>

由于js有些多,这里就贴出了主要的一些代码。另外dom.js中是一些常用的函数。

const domUtils = {
    /**
     * 获取滚动条宽度(避免滚动条出现/消失,页面挤压)
     */
    getScrollBarSize: function() {
        if (scrollBarWidth !== undefined) return scrollBarWidth;

        const outer = document.createElement('div');
        outer.style.visibility = 'hidden';
        outer.style.width = '100px';
        outer.style.position = 'absolute';
        outer.style.top = '-9999px';
        document.body.appendChild(outer);

        const widthNoScroll = outer.offsetWidth;
        outer.style.overflow = 'scroll';

        const inner = document.createElement('div');
        inner.style.width = '100%';
        outer.appendChild(inner);

        const widthWithScroll = inner.offsetWidth;
        outer.parentNode.removeChild(outer);
        scrollBarWidth = widthNoScroll - widthWithScroll;

        return scrollBarWidth;
    },
    /**
     * 生成弹窗随机ID
     */
    generateId: function() {
        return Math.floor(Math.random() * 10000);
    },
    convert: function(str) {
        const c = str.charAt(0);
        return c.toUpperCase() + str.replace(c, '');
    },
    scroll: function(type) {
        const _s = this.convert(type);
        return _docEl['scroll' + _s] || _doc.body['scroll' + _s];
    },
    client: function(type) {
        const _s = this.convert(type);
        return _docEl['client' + _s] || _doc.body['client' + _s];
    },
    getFollowRect: function(follow, oW, oH) {
        let followo;
        let t = typeof follow;
        let rT, rL, sT, sL, _top, _left, _placement;
        let wW = this.client('width');
        let wH = this.client('height');

        // 定位元素(class或id .xxx|#xxx)
        if(t == 'string') {
            followo = document.querySelector(follow);
            rT = Math.round(followo.getBoundingClientRect().top);
            rL = Math.round(followo.getBoundingClientRect().left);
            sT = rT + this.scroll('top');
            sL = rL + this.scroll('left');
            if((rT + oH + followo.offsetHeight) > wH) {
                _top = sT - oH;
                _placement = 'top';
            }else {
                _top = sT + followo.offsetHeight;
                _placement = 'bottom';
            }
            _left = (rL + oW) > wW ? (sL - oW + followo.offsetWidth) : sL;
        } 
        // 定位元素(坐标点 clientX|clientY)
        if(t == 'object') {
            rT = follow[1];
            rL = follow[0];
            sT = rT + this.scroll('top');
            sL = rL + this.scroll('left');
            _top = (rT + oH) > wH ? (sT - oH) : sT;
            _left = (rL + oW) > wW ? (sL - oW) : sL;
        }

        return [_left, _top, _placement];
    },
    // 获取弹窗最大层级
    getZIndex: function(zIndex) {
        for(var $idx = parseInt(zIndex), $elm = document.getElementsByTagName('*'), i = 0, len = $elm.length; i < len; i++)
          $idx = Math.max($idx, $elm[i].style.zIndex)
        return $idx;
    },
    // 获取样式
    getStyle: function(el, styleName) {
        if(!el || !styleName) return;
        return el.currentStyle ? el.currentStyle[styleName] : _doc.defaultView.getComputedStyle(el, null)[styleName];
    },
    on: function(el, event, handle) {
        el.attachEvent ? el.attachEvent('on' + event, handle) : el.addEventListener(event, handle, false);
    },
    off: function(el, event, handle) {
        el.detachEvent ? el.detachEvent('on' + event, handle) : el.removeEventListener(event, handle, false);
    }
}

通过 vue.extend 扩展实例实现函数式调用。挂载了类型为 message、notify、popover 函数式写法。

import Vue from 'vue';
import VueLayer from './vlayer.vue';

let VLayerConstructor = Vue.extend(VueLayer);

let $instance;
let _getInstance = props => {
    return new VLayerConstructor(props)
}

let VLayer = function(options = {}) {
    // ...
}

/**
 * Message 消息提示
 * @param {Object} options 
 */
VLayer.message = function(options) {
    typeof options == 'string' && (options = { content: options });
    return VLayer({
        icon: 'info', anim: 'fadeInUp', position: 't', lockScroll: false, shade: false, time: 2, layerStyle: 'margin-top:15px;',
        ...options,
        title: null, type: 'message'
    })
}

/**
 * Notification 通知提醒
 * @param {Object} options 
 */
VLayer.notify = function(options) {
    typeof options == 'string' && (options = { content: options });
    return VLayer({
        anim: 'fadeInRight', position: 'rt', lockScroll: false, shade: false, xclose: true, time: 4.5, layerStyle: 'margin:20px 0 0 -20px;',
        ...options,
        type: 'notify'
    })
}

/**
 * Popover 弹出框 | Popconfirm 气泡确认框
 * @param {Object} options 
 */
VLayer.popover = function(options) {
    return VLayer({
        anim: 'fadeIn', lockScroll: false, shade: false, xclose: true,
        ...options,
        type: 'popover'
    })
}

VLayer.install = () => {
    Vue.prototype['$vlayer'] = VLayer;
    Vue.component('v-layer', VueLayer);
}

export default VLayer;

标题区可以拖拽,也可以自定义拖拽手柄。设置 drag: '.xxx',或者 drag: false 禁止拖拽。

<v-layer 
    v-model="showDragable" 
    title="拖放弹窗" 
    xclose 
    maximize 
    :area="['', '580px']" 
    drag="#dragGuesture" 
    dragOut
>
    <div slot="content">
        <p id="dragGuesture" style="padding:30px;">
            <span style="background:#ff0;color:#00e0a1;">我是自定义拖拽抓手 drag:'#dragGuesture' <br>拖动我试一试!<br>
            <em style="color:red;">设置drag:false可禁止拖拽!</em><br>
            <em style="color:red;">设置dragOut:true可拖拽到窗口外!</em>
            </span>
        </p>
        <img @click="handleXXX" src="xxx.jpg" style="max-width:100%;" />
    </div>
</v-layer>

注意:使用popover时候,需要传入follow: '#xxxx' 定位元素。

let $fw = this.$vlayer.popover({
    follow: '#popover',
    icon: 'warning',
    content: '这是一段内容确定删除吗?', 
    time: null, 
    xclose: false,
    btns: [
        {text: 'no', click: () => { $fw.close(); }},
        {text: 'yes', click: () => this.handleXXX()},
    ],
    onClose: function() {
        this.$vlayer.message({content: 'success closed', icon: 'success'})
    }
});

另外还支持iframe类型弹窗,设置type: 'iframe',content传入网址就行。

<!-- iframe弹窗 -->
<v-layer
    title="iframe弹窗"
    content="https://cn.vuejs.org/"
    v-model="showIframe"
    type="iframe"
    lock-scroll="false"
    xclose
    maximize
    resize
    :area="['915px', '595px']"  
/>

还支持自定义弹窗位置position,默认是auto居中(['100px','50px'] | t | r | b | l | lt | rt | lb | rb)

<!-- 自定义弹窗位置 -->
<v-layer v-model="showPosition" xclose maximize drag=".dragImage" :position="rb">
    <img class="dragImage" src="xxx.jpg" style="max-width:100%;" />
</v-layer>

好了,基于vue.js开发网页弹窗组件就介绍到这里。希望能喜欢哈!😁

最后附上最近的两个实例

Nuxt+vue+vant仿微信聊天app项目|nuxt.js聊天室

vue仿探探|Tinder卡牌式堆叠效果

 

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

xiaoyan_2018

你的鼓励将是我持续作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值