封装组件——全局倒计时loading框

前言

对于之前封装的loading组件想要进行一个优化,然后想到可以不用在页面中添加template引入组件模板,而是直接将组件挂载到vue实例上,使用this原型调用组件并传值

需求

需要一个全局倒计时loading框,倒计时可自定义,提示信息可自定义

实现

组件内容

loading.vue

<template>
  <section v-if="show">
    <div class='mock'>
      <div class='dot-div'>
        <div class="dot dot-one"></div>
        <div class="dot dot-two"></div>
        <div class="dot dot-three"></div>
        <div class="dot dot-four"></div>
      </div>
      <div class="wrapp">
        <div class="
           loading-text">
          {{message}}
        </div>
        <div class="time-text">
          <span class="tome-countdown">{{count}}</span>
          <span class="sec">s</span>后回到首页
        </div>
      </div>
    </div>
  </section>
</template>
<script type="text/babel">
export default {
  data () {
    return {
      count: 0,
      timer: null,
      show: true,
      message: '',
    };
  },
  methods: {
  	/**
     * 开启倒计时
     */
    startTimer () {
      if (this.count > 0) {
        this.timer = setTimeout(() => {
          this.startTimer();
          this.count -= 1;
        }, 1000);
      } else {
        clearTimeout(this.timer);
        this.timer = null;
        this.show = false;
      }
    },
    /**
     * 清除计时器
     */
    clearTimer () {
      clearTimeout(this.timer);
    },
    /**
     * 关闭倒计时
     */
    hide () {
      this.count = 0;
      this.show = false;
      this.clearTimer();
    }
  },
  mounted () {
    this.startTimer();//开启倒计时
  },
};
</script>

封装组件实例

loading.js

import Vue from 'vue'
import Main from './loading.vue'

const loadingConstructor = Vue.extend(Main)

let instance;

const loading = function (options) {
  if (Vue.prototype.$isServer) return;
 //组件实例化
  instance = new loadingConstructor({
    data: options
  })
  //组件挂载
  instance.$mount();
  document.body.appendChild(instance.$el);
}
//将隐藏方法传给loading的hide属性
loading.hide = function () {
  instance.hide();
}

export default loading;

注册及使用

注册

main.js里注册

//引入loading.js
import loading from './components/loading'

Vue.prototype.$myloading = loading//展示loading
Vue.prototype.$hideloading = loading.hide//隐藏loading

使用

显示loading框:

this.$myloading({
      message: '请稍候',
      count: 10
    })

隐藏

this.$hideloading()

效果

在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值