Vue2封装自定义全局Loading组件

前言

在开发的过程中,点击提交按钮,或者是一些其它场景总会遇到Loading加载框,PC的一些UI库也没有这样的加载框,无法满足业务需求,因此可以自己自定义一个,实现过程如下。

效果图

如何封装?

第1步:创建要封装成全局组件的文件

html 复制代码
<template>
  <div class="loading"
       v-show="msg.show">
    <div class="load-box">
      <!-- 图片放在文末,自行右键另存为 -->
      <img src="@/assets/common/load.png">
      <span>{{ msg.title }}</span>
    </div>
  </div>
</template>

<script>
export default {
  name: 'SelfLoading',

  props: {
    msg: {
      type: Object,
      default: () => ({
        show: false,
        title: '加载中...'
      })
    }

  },

  methods: {
    // 显示loading的方法
    show (title = '加载中...') {
      this.msg.show = true
      this.msg.title = title
    },

    // 隐藏loading的方法
    hide () {
      this.msg.show = false
    }
  }
}
</script>

<style lang="scss" scoped>
.loading {
  width: 100%;
  height: 100%;
  position: fixed;
  top: 0;
  left: 0;
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 9999;
  .load-box {
    background-color: rgba(0, 0, 0, 0.5);
    width: 100px;
    height: 100px;
    border-radius: 5px;
    box-shadow: 0px 1px 15px rgba(0, 0, 0, 0.5);
    color: #fff;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    letter-spacing: 0.8px;
    font-size: 13px;
    img {
      width: 30px;
      margin-bottom: 8px;
      animation: rotate 0.8s linear infinite;
    }
  }
}

@keyframes rotate {
  to {
    transform: rotate(360deg);
  }
}
</style>

第2步:注册组件

Loading这类的通用组件一般定义为全局组件,那么直接在main.js文件中全局注册。

javascript 复制代码
import SelfLoading from '@/components/Loading'
Vue.component('SelfLoading', SelfLoading)

第3步:使用组件

html 复制代码
<template>
  <!-- 全局Loading -->
  <self-loading ref="loadingRef" />
</template>

<script>
export default {
  // 仅做示例
  created () {
    // 开启全局Loading,不传参默认为 '加载中...'
    this.$refs.loadingRef.show('上传中...')
  },

  // 仅做示例
  beforeDestroy () {
    // 隐藏全局Loading
    this.$refs.loadingRef.hide()
  }
}
</script>

图片在这里

图片右击另存为即可,好像会有CSDN自动添加的水印,不太知道怎么去除,需要原图的可以在评论区留下你的邮箱地址。

相关推荐
程序员老赵19 小时前
Docker 部署 ZLMediaKit:轻松搭建高性能流媒体服务平台
前端·javascript·后端
拾年27520 小时前
前后端分离开发,别再"傻等"后端接口了——聊聊前端接口工程
前端·javascript·react.js
breeze jiang20 小时前
CSS 三栏布局怎么写:Flex、Grid 完整方案与 BFC 区别
前端·css
SendTomo20 小时前
SendTomo稳定传输三大核心策略
javascript·网络协议·webrtc·html5·p2p
天才熊猫君20 小时前
从“改自己”到“改布局”——拖拽调整的通用设计思路
前端·javascript
何时梦醒20 小时前
CSS 三栏布局与 BFC 深度解析:Float、Flex、Grid 三种方案一网打尽
前端·css·面试
weixin_BYSJ198720 小时前
springboot小区物业管理小程序---附源码45555
java·javascript·spring boot·python·django·flask·php
默_笙20 小时前
🍳 受控组件和非受控组件,我纠结了一整天,最后用"房东和租客"讲明白了
前端·javascript
烬羽20 小时前
CSS 三栏布局:`margin-left: -100%` 凭什么把侧栏「拽」回上一行?彻底搞懂负 margin
css·面试·前端框架
BreezeJiang20 小时前
写了 display:flex,为什么三栏布局还没完成?
前端·css