单例模式的loading组件封装

该文介绍了如何创建一个Vue组件——Loading,包含两种模式(带遮罩和不带遮罩),并使用单例模式管理,确保应用中只有一个Loading实例。组件内部使用SVG绘制旋转的圆圈效果,并在main.js中全局注册,供所有组件使用。

1、创建一个Loading组件的文件夹包含一个js文件,和一个vue文件 

loading.vue里面写的就是loading的html内容和样式,这里是两个旋转的圆圈的效果,并且有两种模式,一个带遮罩一个不带遮罩。

loading.vue

<template>
  <div id="loadingDiv">
    <div class="my_loading_mask" :class="[{'has_mask':mask}]">
        <div class="el-loading-spinner">
            <svg  class="circular" viewBox="0 0 60 60"> 
                <circle class="path path_1" cx="30" cy="30" r="15" fill="none"/> 
                <circle class="path path_2" cx="30" cy="30" r="25" fill="none"/> 
            </svg>
        </div>
    </div>
  </div>
</template>

<script>
export default {
    data(){
        return {
            mask: false
        }
    }
};
</script>

<style lang="scss" scoped>
.my_loading_mask {
  width: 100vw;
  height: 100vh;
  background: transparent;
  position: fixed;
  top: 0;
  left: 0;
  z-index: 9999;
  &.has_mask{
    background: rgba(0, 0, 0, 0.4);
    .el-loading-spinner .path{
        stroke: #fff
    }
  }
  
  .el-loading-spinner .path_1{
    stroke-dasharray: 70,150;
    animation: loading-rotate 1.2s linear infinite;
    transform-origin: center;
  }
  .el-loading-spinner .path_2{
    stroke-dasharray: 130,150;
    transform-origin: center;
    animation: loading-rotate 1.4s linear infinite;
  }
  .el-loading-spinner .circular{
    height:60px;
    width: 60px;
    animation: none;
  }
}

</style>

 

loading.js

import Vue from 'vue';
import loadingVue from './loading.vue';


const LoadingConstructor = Vue.extend(loadingVue);


let Loading = (function () {
    function _loading() {
        this.mask = false
        this.instance = null
        this.loading = function (mask = false) {
            this.mask = mask
            if (!this.instance) {
                this.addLoading()
            }
        }
        this.addLoading = function () {
            this.instance = new LoadingConstructor({
                el: document.createElement('div'),
                data: {
                    mask: this.mask
                }
            });
            document.body.appendChild(this.instance.$el)
        }
        this.close = function () {
            if (this.instance) {
                document.body.removeChild(this.instance.$el)
            }
            this.instance = null
        }
    }
    return function () {
        if (!_loading.instance) {
            _loading.instance = new _loading()
        }
        return _loading.instance
    }
})()


export default new Loading()

这里直接使用单例模式输出一个Loading的实例,实例有loading方法,用来新增一个loading,默认没有遮罩的。

addLoading方法生成一个dom,插入到body里面。

close方法把dom移除。

然后在main.js里面引入这个js,再挂载在Vue实例上面,这样所以的组件都可以直接使用了,而且不用担心生成多个loading。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值