基於Vue.js PC桌面端彈出框元件|vue自定義彈層元件|vue模態框

xiaoyan2017發表於2020-11-02

vue.js構建的輕量級PC網頁端互動式彈層元件VLayer。

前段時間有分享過一個vue移動端彈窗元件,今天給大家分享一個最近開發的vue pc端彈出層元件。

VLayer 一款集Alert、Dialog、Message、Notification、ActionSheet、Toast、Popover、Popconfirm等眾多功能於一身的輕量級pc彈層元件。通過精巧的邏輯、佈局解決複雜的對話方塊功能,為你呈現多樣化彈出框效果!

VLayer 在設計開發之初借鑑了業界有名的Layer彈窗、Element-UI、iView等元件化設計思想。

  • 提供了2種呼叫方式(標籤式 | 函式式)
  • 12+彈窗型別(toast、footer、actionsheet、actionsheetPicker、android/ios、contextmenu、drawer、iframe、message、notify、popover)
  • 內建7種彈窗動畫(scaleIn | fadeIn | footer | fadeInUp | fadeInDown | fadeInLeft | fadeInRight)

◆ 引入元件

在main.js中引入vlayer元件。

 import VLayer from './components/vlayer' 

 Vue.use(VLayer) 

vlayer支援標籤式函式式兩種呼叫方式。

  • 標籤式寫法
<v-layer 
    v-model="showConfirm"
    title="標題內容"
    content="<div style='color:#00e0a1;padding:20px;'>這裡是內容資訊!</div>"
    xclose
    z-index="2001"
    lockScroll="false"
    resize
    dragOut
    :btns="[
        {text: '關閉', click: () => showConfirm=false},
        {text: '確認', style: 'color:#f90;', click: handleXXX},
    ]"
/>
  • 函式式寫法

vlayer同樣支援函式式寫法  this.$vlayer({...})  支援30+中引數靈活配置。

注意:當使用型別為message | notify | popover彈窗時候,呼叫方式只能是函式式 this.$vlayer.message({...})  this.$vlayer.notify({...})  this.$vlayer.popover({...}) 

let $vlayero = this.$vlayer({
    title: '標題內容',
    content: '<div style='color:#00e0a1;padding:20px;'>這裡是內容資訊!</div>', 
    xclose: true,
    zIndex: 2001,
    lockScroll: false,
    resize: true,
    dragOut: true,
    btns: [
        {text: '關閉', click: () => { $vlayero.close(); }},
        {text: '確認', click: () => this.handleXXX()},
    ]
});

◆ 一覽效果

◆ 實現過程

  • vlayer預設配置引數
@@Props
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)
------------------------------------------
@@$emit
open        開啟彈出層時觸發(@open="xxx")
close       關閉彈出層時觸發(@close="xxx"------------------------------------------
@@Event
onOpen      開啟彈窗回撥
onClose     關閉彈窗回撥
  • vlayer彈窗模板
<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" @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     vue.js自定義pc端彈窗元件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--;
          }
          // 清除彈窗樣式
          vlayero.style.width = vlayero.style.height = vlayero.style.top = vlayero.style.left = '';
          ocnt.style.height = '';
          omax && omax.classList.contains('maximized') && omax.classList.remove('maximized');
          this.vlayerOpts.isBodyOverflow && (document.body.style.overflow = '');

          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>

dom.js中是一些常用的函式。當彈窗出現,滾動條隱藏,避免出現頁面移位。

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;
},

vlayer彈窗通過 Vue.extend 擴充套件函式實現函式式呼叫。

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="handleInfo" src="xxx.jpg" style="max-width:100%;" />
    </div>
</v-layer>
  • message 資訊框

<!-- 普通提示 -->
this.$vlayer.message('這是一條提示資訊');

<!-- 成功提示 -->
this.$vlayer.message({content: '這是一條成功的提示', icon: 'success'});

<!-- 錯誤提示(自定義背景) -->
this.$vlayer.message({content: ' 這是一條錯誤的提示', icon: 'error', layerStyle: 'background:#ffefe6;color:#ff3838;margin-top:15px;'});
  • notification 通知框

<!-- 成功通知 -->
this.$vlayer.notify({title: '成功', content: '這是一條成功的提示', icon: 'success'});
  • popover / popconfirm 氣泡框

<!-- 使用方法和上面差不多,只不過需要加上follow定位元素 -->
let $fw = this.$vlayer.popover({
    follow: '#popover4',
    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']"  
/>

okay,以上就是基於vue.js實現pc端彈窗的一些分享,希望對大家有所幫助!??

最後附上vue移動端彈窗及nuxt例項專案

vue.js移動端彈框:https://www.cnblogs.com/xiaoyan2017/p/13776977.html

nuxt.js+vue聊天例項:https://www.cnblogs.com/xiaoyan2017/p/13823195.html

 

相關文章