Vue3自定义插件实现全局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>

最后的效果就是: 

猜你喜欢

转载自blog.csdn.net/weixin_44786530/article/details/130832599