Vue3自定义插件实现全局Loading效果过程
更新时间:2026年03月11日 16:07:53 作者:1024小神
文章介绍了如何在Vue项目中实现一个全局的loading效果,通过创建一个loading组件,并将其封装成一个插件,在main.ts中进行全局挂载,使得在应用的任何地方都可以通过`LOADING`属性来控制loading状态,最后在App.vue中引用该插件,从而实现全局loading效果
使用组件的形式
实现全局loading效果:

在项目中添加一个文件夹
plugin/loading,并新建一个loading.vue组件:

loading.vue组件代码:
<template>
<div v-if="loading" class="loading">Loading</div>
</template>
<script setup lang="ts">
import { ref } from 'vue'
const loading = ref(false)
const show = () => {
loading.value = true
console.log('show方法执行了')
}
const hide = () => {
loading.value = false
console.log('hide方法执行了')
}
defineExpose({
show,
hide
})
</script>
<style scoped>
.loading {
position: fixed;
top: 0;
display: flex;
align-items: center;
justify-content: center;
font-size: 30px;
width: 100vw;
height: 100vh;
opacity: 0.5;
background-color: grey;
color: white;
z-index: 999;
}
</style>
新建一个index.ts插件文件
将loading组件加载进去,并且给vue对象全局挂载LOADING属性
import type { App } from 'vue'
import { createVNode, render } from 'vue'
import loading from './loadIng.vue'
export default {
install(app: App) {
console.log('全局Loadig插件执行了')
// 将vue组件转为VNode,然后渲染到页面上
const VNode = createVNode(loading)
render(VNode, document.body)
// 给Vue对象全局挂载属性show、hide
app.config.globalProperties.LOADING = {
show: VNode.component?.exposed?.show,
hide: VNode.component?.exposed?.hide
}
console.log('挂载点属性:', VNode.component?.exposed, app.config.globalProperties.LOADING)
}
}
在main.ts中挂载这个组件

在main.ts中声明LOADING属性
import './assets/main.css'
import { createApp } from 'vue'
import { createPinia } from 'pinia'
import ElementPlus from 'element-plus'
import 'element-plus/dist/index.css'
import App from './App.vue'
import router from './router'
import loading from './plugin/loading'
const app = createApp(App)
app.use(createPinia())
app.use(router)
// 自定义插件全局loading
app.use(loading)
app.use(ElementPlus)
// 定义全局变量和全局函数
app.config.globalProperties.env = "dev"
app.config.globalProperties.filter = {
format<T>(content:T){
return "格式化后的内容" + content
}
}
// 解决Vue中的全局变量和函数报错问题
interface Filter {
format<T>(content:T):string
}
interface LOADING {
show():null
hide():null
}
declare module 'vue' {
export interface ComponentCustomProperties {
filter: Filter,
env:string,
LOADING:LOADING
}
}
app.mount('#app')
在App.vue中引用这个插件
<template>
<div class="app">
主页测试全局loading插件
<button @click="showLoading">点击加载loading</button>
</div>
</template>
<script setup lang="ts">
import { getCurrentInstance } from 'vue'
const app = getCurrentInstance()
const showLoading = ()=>{
// const app = getCurrentInstance()
app?.proxy?.LOADING.show()
console.log("点击了loading", app);
// 5秒之后取消加载
setTimeout(() => {
app?.proxy?.LOADING.hide()
}, 5000);
}
</script>
<style scoped>
.app{
width: 100vw;
height: 100vh;
font-size: 30px;
background-color: orange;
}
</style>
最后的效果就是:

总结
以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。
相关文章
vue-resource + json-server模拟数据的方法
本篇文章主要介绍了vue-resource + json-server模拟数据的方法,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧2017-11-11


最新评论