vue仿layer.js彈層元件vlayer

xiaoyan2015發表於2020-11-11

介紹

VLayer 一款基於vue.js開發的pc網頁端彈窗元件。集msg|alert|dialog|notify|popover|toast|actionsheet等眾多功能於一身的漂亮彈框元件。支援拖拽、縮放、最大化|全屏等功能。

如上圖效果,下面就簡單介紹下具體實現過程。

快速引入

main.js中全域性引入元件。

import VLayer from './components/vlayer'
Vue.use(VLayer)

vlayer支援標籤函式2種寫法。

標籤式寫法

<v-layer 
    v-model="isConfirm"
    title="標題"
    content="<div style='color:#06f;padding:10px;'>彈窗內容資訊!</div>"
    xclose
    z-index="2020"
    lockScroll="false"
    resize
    dragOut
    :btns="[
        {text: '關閉', click: () => isConfirm=false},
        {text: '確定', style: 'color:#f90;', click: handleFn},
    ]"
/>

函式式寫法

let $el = this.$vlayer({
    title: '標題',
    content: '<div style='color:#06f;padding:10px;'>彈窗內容資訊!</div>', 
    xclose: true,
    zIndex: 2020,
    lockScroll: false,
    resize: true,
    dragOut: true,
    btns: [
        {text: '關閉', click: () => { $el.close(); }},
        {text: '確定', click: () => this.handleFn()},
    ]
});

預覽圖











彈窗引數

支援30+種自定義引數配置,讓你的彈窗效果千變萬化。

@@預設引數
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        彈窗自動關閉秒數(123)
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>

彈窗標題區域預設是可以拖動的,也可以根據需要自定義拖拽手柄 drag: '#xxxx',或者設定 drag: false 來禁止彈窗拖拽功能。
設定 dragOut: true 窗體可以拖拽到瀏覽器外部
支援自定義彈窗顯示位置,預設是auto居中['150px','100px'] | t | r | b | l | lt | rt | lb | rb

<!-- 自定義彈窗位置 -->
<v-layer v-model="showPosition" xclose maximize drag=".dragImg" :position="rb">
    <img class="dragImg" src="xxx.jpg" />
</v-layer>

設定 fullscreen: true 一開啟就全屏顯示。maximize: true 開啟最大化按鈕。

ok,今天就分享到這裡。感興趣的同學可以自己動手試試哈!??

最後附上vue移動端彈窗及例項
基於vue.js自定義移動端對話方塊元件VPopup
基於nuxt.js+vue仿微信App介面聊天例項

本作品採用《CC 協議》,轉載必須註明作者和本文連結
本文為原創文章,未經作者允許不得轉載,歡迎大家一起交流 QQ(282310962) wx(xy190310)

相關文章