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自动添加的水印,不太知道怎么去除,需要原图的可以在评论区留下你的邮箱地址。

相关推荐
阿蒙Amon17 小时前
JavaScript学习笔记:16.模块
javascript·笔记·学习
苏打水com17 小时前
第十七篇:Day49-51 前端工程化进阶——从“手动”到“自动化”(对标职场“提效降本”需求)
前端·javascript·css·vue.js·html
『 时光荏苒 』17 小时前
使用Vue播放M3U8视频流的方法
前端·javascript·vue.js
消防大队VUE支队18 小时前
🗓️ 2262年将有两个春节!作为前端的你,日历控件真的写对了吗?
前端·javascript
鸭蛋超人不会飞18 小时前
axios简易封装,适配H5开发
前端·javascript·vue.js
前端不太难18 小时前
Vue 项目路由 + Layout 的最佳实践
前端·javascript·vue.js
巴拉巴拉~~18 小时前
Flutter 通用列表刷新加载组件 CommonRefreshList:下拉刷新 + 上拉加载 + 状态适配
前端·javascript·flutter
Asus.Blogs18 小时前
golang格式化打印json
javascript·golang·json
码途潇潇18 小时前
数据大屏常用布局-等比缩放布局(Scale Laylout)-使用 CSS Transform Scale 实现等比缩放
前端·css
parade岁月18 小时前
JavaScript Date 的那些事
javascript