【Vue3】自定义 Vue3 插件(全局实现页面加载动画)

ts 复制代码
// main.ts
import { createApp } from 'vue'
import App from './App.vue'
import Loading from "./components/Loading/index.ts";

const app = createApp(App)
type Lod = {
    show: () => void,
    hide: () => void
}
//编写ts loading 声明文件放置报错 和 智能提示
declare module '@vue/runtime-core' {
    export interface ComponentCustomProperties {
        $loading: Lod
    }
}

app.use(Loading)
app.mount('#app')
js 复制代码
<template>
<!--  App.vue-->
  <div>
    <img id="img" width="400" height="400" src="./assets/unnamed.jpg" alt=""/>
  </div>
</template>

<script setup lang="ts">
import {getCurrentInstance} from "vue";

const instance = getCurrentInstance()
instance?.proxy?.$loading.show()
setTimeout(() => {
  instance?.proxy?.$loading.hide()
}, 5000)

</script>

<style>

</style>
ts 复制代码
// /components/Loading/index.ts
import type {App, VNode} from 'vue'
import {createVNode, render} from "vue";
import Loading from './index.vue'

export default {
    install(app: App) {
        const Vnode: VNode = createVNode(Loading)
        render(Vnode, document.body)
        app.config.globalProperties.$loading = {
            show: Vnode.component?.exposed?.show,
            hide: Vnode.component?.exposed?.hide,
        }
    }
}
js 复制代码
<template>
<!--  components/Loading/index.vue-->
  <div v-if="isShow" class="loading">
    <div class="loading-content">Loading...</div>
  </div>
</template>

<script setup lang='ts'>
import { ref } from 'vue';
const isShow = ref(false) //定位loading 的开关

const show = () => {
  isShow.value = true
}
const hide = () => {
  isShow.value = false
}
//对外暴露 当前组件的属性和方法
defineExpose({
  isShow,
  show,
  hide
})
</script>



<style scoped lang="less">
.loading {
  position: fixed;
  inset: 0;
  background: rgba(0, 0, 0, 0.8);
  display: flex;
  justify-content: center;
  align-items: center;
  &-content {
    font-size: 30px;
    color: #fff;
  }
}
</style>
相关推荐
爱泡脚的鸡腿3 分钟前
uni-app D3实战(小兔仙)
前端
嬉皮客14 分钟前
Gird布局详解
前端·css
烛阴14 分钟前
C#常量(const)与枚举(enum)使用指南
前端·c#
Wect17 分钟前
学习React-DnD:实现多任务项拖拽-useDrag处理
前端
mucheni25 分钟前
迅为RK3568开发板OpeHarmony学习开发手册-修改应用程序名称
linux·前端·学习
WebGirl28 分钟前
SSE服务
前端
Mintopia33 分钟前
🛰️ 低带宽环境下的 AIGC 内容传输优化技术
前端·人工智能·trae
浮游本尊34 分钟前
Vue.js 项目静态资源 OSS 部署完整实现指南
vue.js
h***346338 分钟前
Nginx 缓存清理
android·前端·后端
Mintopia1 小时前
⚡Trae Solo Coding 的效率法则
前端·人工智能·trae