最近在做一个让请求数据的时候要有一个全屏的弹框,我就自己写了一个loading动画,以api的方式调用,废话不说了直接上代码!!!
// components/Loading/loading.js
/* 组件分为全局注册,局部注册,通过js的方式去注册(这种组件只适用于消息提示,loading展示,成功的展示) */
import Loading from './index'
export default (Vue) => {
Vue.prototype.$loading = {
_component: '',
show () {
const LoadingClass = Vue.extend(Loading) /* 生成组件类 */
this._component = new LoadingClass() /* 实例化组件 */
this._wrap = document.createElement('div')
document.body.appendChild(this._wrap) /* 把这个dom放到body里面去 */
this._component.$mount(this._wrap) /* 执行渲染 */
},
hide () {
this._component.$destroy()
}
}
}
// components/Loading/index.vue
<template>
<!-- 封装的自定义全局动画 -->
<div class="loading-wrap">
<a href="javascript:;" class="loading"></a>
</div>
</template>
<script>
export default {
name: 'loading',
destroyed () {
/* 我们自己手动注册的事件应该手动的销毁 */
console.log(this.$el, '世界真奇妙')
document.body.removeChild(this.$el)
}
}
</script>
<style lang="scss" scoped>
.loading-wrap {
@include wh(100vw, 100vh);
background: rgba(0, 0, 0, 0.5);
position: fixed;
top: 0;
left: 0;
display: flex;
z-index: 10000;
.loading {
margin: auto;
width: 140px;
height: 140px;
background-image: url(https://img.dmallcdn.com//dshop/201903/40208262-8001-4c19-ad20-370a039ed243);
background-repeat: no-repeat;
background-position: 0 0;
background-size: auto 140px;
animation: loading .9s steps(25) infinite;
}
}
@keyframes loading {
from {
background-position: 0 0;
}
to {
background-position: -3500px 0;
}
}
</style>
使用:
// 显示
this.$loading.show() // 有可能$loading在Vue原型挂在之前可能有,到时候只需改一下名
// 隐藏
this.$loading.hide()