Vue3 中写一个全局loaing插件
1.首先定义一个loading组件
plugins/Loading/loading.vue
<template>
<div class="loading">加载中...</div>
</template>
<script>
export default {
name: 'loading'
}
</script>
<style scoped>
.loading {
position: fixed;
width: 100%;
height: 100%;
left: 0;
top: 0;
background-color: rgba(0, 0, 0, 0.5);
color: white;
display: flex;
justify-content: center;
align-items: center;
}
</style>
2.当调用open方法时将组件挂载到body节点上, 当调用close方法时将组件移除。
plugins/Loading/index.js
import { createApp } from 'vue'
import Loading from './Loading.vue'
export default {
instance: null,
parent: null,
open() {
this.instance = createApp(Loading)
this.parent = document.createElement('div')
document.body.appendChild(this.parent)
this.instance.mount(this.parent)
},
close() {
this.instance.unmount(this.parent)
document.body.removeChild(this.parent)
}
}
3. 将插件导出,放在app属性中
main.ts
import loading from '@/plugins/loading/index.js'
app.config.globalProperties.$loading = loading
4.组件中使用loading
this.$loading.open()
setTimeout(() => {
this.$loading.close()
}, 2000)

浙公网安备 33010602011771号