【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>
相关推荐
伍哥的传说11 分钟前
鸿蒙系统(HarmonyOS)应用开发之手势锁屏密码锁(PatternLock)
前端·华为·前端框架·harmonyos·鸿蒙
yugi98783813 分钟前
前端跨域问题解决Access to XMLHttpRequest at xxx from has been blocked by CORS policy
前端
浪裡遊24 分钟前
Sass详解:功能特性、常用方法与最佳实践
开发语言·前端·javascript·css·vue.js·rust·sass
旧曲重听11 小时前
最快实现的前端灰度方案
前端·程序人生·状态模式
默默coding的程序猿1 小时前
3.前端和后端参数不一致,后端接不到数据的解决方案
java·前端·spring·ssm·springboot·idea·springcloud
夏梦春蝉1 小时前
ES6从入门到精通:常用知识点
前端·javascript·es6
归于尽2 小时前
useEffect玩转React Hooks生命周期
前端·react.js
G等你下课2 小时前
React useEffect 详解与运用
前端·react.js
我想说一句2 小时前
当饼干遇上代码:一场HTTP与Cookie的奇幻漂流 🍪🌊
前端·javascript
funnycoffee1232 小时前
Huawei 6730 Switch software upgrade example版本升级
java·前端·华为