【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>
相关推荐
程序员修心8 分钟前
CSS 选择器知识点
前端·css·css3
梦65012 分钟前
React + FullCalendar 实现高性能跨天事件日历组件
前端·react.js·前端框架
C_心欲无痕13 分钟前
react - 组件之间的通信
前端·javascript·react.js
Lupino15 分钟前
Node.js 与 Haskell 混合网络编程踩坑记:TCP 粘包与状态不一致引发的“死锁”
javascript·node.js
走粥21 分钟前
JavaScript Promise
开发语言·前端·javascript
-CRzy21 分钟前
CTF之web-信息收集
前端
神算大模型APi--天枢64625 分钟前
合规落地加速期,大模型后端开发与部署的实战指南
大数据·前端·人工智能·架构·硬件架构
四瓣纸鹤27 分钟前
F2图表柱状图添加文本标注
前端·javascript·antv/f2
inferno28 分钟前
HTML基础(第二部分)
前端·html
Dreamcatcher_AC34 分钟前
Ajax技术:前后端交互全解析
前端·ajax