当前位置:   article > 正文

vue3 自定义全局loading组件 (PC和移动端都非常适用)_vue3全局loading

vue3全局loading

前言

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

效果图(loading样式可以自定义)

代码实现

自定义组件 loading.vue(图片放在文末,自行右键另存为)

<template>
  <div class="loading" v-show="msg.show">
    <div class="load-box">
      <img src="@/assets/img/load.png">
      <!--<img src="@/assets/img/loading_white.png">-->
      <span>{{msg.title}}</span>
    </div>
  </div>
</template>

<script>
export default {
  name: 'loading',
  props: {
    msg: Object,
  }
}
</script>

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

@keyframes rotate{
  to{
    transform: rotate(360deg);
  }
}
</style>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50

utils/loading.js 创建封装js控制显示和隐藏,以及需要显示的文字

import { createApp, reactive } from 'vue'

import myLoad from '@/components/Loading/loading.vue'

const msg = reactive({
  show: false,
  title: '加载中...'
})

const $loading = createApp(myLoad, {msg}).mount(document.createElement('div'))
const load = {
  show(title: any = msg.title) { // 控制显示loading的方法
    msg.show = true
    msg.title = title
    document.body.appendChild($loading.$el)
  },

  hide() { // 控制loading隐藏的方法
    msg.show = false
  }
}
export  { load }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22

页面使用

import { load } from '@/utils/loading.js';

// 在需要使用时调用show方法
// 例如在指定api调用,或者其他耗时操作时打开loading
// 不传参默认为 加载中...
load.show();
load.show('登录中...');

//在加载完成时关闭
load.hide();
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10

小结

  • 大家可以根据自己的习惯和方式来选择用哪一张图片,也可以动态传参改变。
  • 样式是仿照移动端的加载框,我是不习惯用那种全屏的加载,大家也可以把样式改为全屏的加载
  • 为了避免在加载的过程,用户点击页面其它元素,所以本文的样式层级很高,大家可以自行去更改

图片在这里

图片右击另存为即可,但是这里有水印,大家也可以去图标库找其它的加载图标代替,效果也是一样的

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/小丑西瓜9/article/detail/218792
推荐阅读
相关标签
  

闽ICP备14008679号