【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>
相关推荐
灰灰勇闯IT4 分钟前
Flutter for OpenHarmony:布局组件实战指南
前端·javascript·flutter
⑩-27 分钟前
Vue框架学习
前端·vue.js·学习
a程序小傲31 分钟前
京东Java面试被问:基于Gossip协议的最终一致性实现和收敛时间
java·开发语言·前端·数据库·python·面试·状态模式
小二·33 分钟前
Python Web 开发进阶实战:AI 原生应用商店 —— 在 Flask + Vue 中构建模型即服务(MaaS)与智能体分发平台
前端·人工智能·python
Devlive 开源社区41 分钟前
技术日报|推理RAG文档索引PageIndex登顶日增1374星,React视频工具Remotion二连冠进前二
前端·react.js·前端框架
xkxnq42 分钟前
第三阶段:Vue 路由与状态管理(第 45 天)(路由与状态管理实战:开发一个带登录权限的单页应用)
前端·javascript·vue.js
编程大师哥43 分钟前
JavaScript 和 Python 哪个更适合初学者?
开发语言·javascript·python
Irene19911 小时前
Vue 3 中的具名插槽仍然完全支持,Vue 2 的旧语法 Vue 3 中已废弃
vue.js·slot
方方洛1 小时前
技术实践总结:schema-bridgion:json、xml、yaml、toml文件相互转换
xml·前端·typescript·node.js·json
2601_949575861 小时前
Flutter for OpenHarmony二手物品置换App实战 - 自定义组件实现
android·javascript·flutter