Vue3封装全局插件

定义一个全局加载组件

一、首先定义dom元素

定义一个index.vue文件

复制代码
<template>
    <div class="loading">
        loading...
    </div>
</template>
<script setup lang="ts">

</script>
<style scoped>
.loading {
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 30px;
    color: #fff;
    background: rgba(0, 0, 0, 0.8);
    height: 100vh;
}
</style>

第二步给dom元素添加,控制显示的开关和方法,然后通过defineExpose暴露出去

复制代码
<script setup lang="ts">
import { ref } from "vue"
const isShow = ref<boolean>(false);
const show = () => {
    isShow.value = true
}
const hide = () => {
    isShow.value = false
}
defineExpose({
    isShow,
    show,
    hide
})
</script>
二、把组件渲染到全局

定义一个index.ts把组件暴露出去

createVNode创建虚拟节点,render把节点渲染到body,然后创建一个全局变量方便操作$Loading

复制代码
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,
        }
    }
}
三、注册组件
复制代码
import { createApp } from 'vue'
import App from './App.vue'
import loading from './components/loading'

const app = createApp(App)

type Lod = {
    show():void,
    hide():void
}

declare module 'vue' {
    export interface ComponentCustomProperties {
        $Loading: Lod
    }
}

app.use(loading)
app.mount('#app')

使用

复制代码
<template>
  <div class="">

  </div>
</template>
<script setup lang="ts">
import { getCurrentInstance } from 'vue';
const app = getCurrentInstance();
app?.proxy?.$Loading.show();
setTimeout(() => {
  app?.proxy?.$Loading.hide();
}, 2000)
</script>
<style scoped></style>
相关推荐
huohaiyu1 小时前
从URL到页面的完整解析流程
前端·网络·chrome·url
阿星AI工作室3 小时前
一个简单Demo彻底理解前后端怎么连的丨Figma + Supabase + Vercel
前端·人工智能
aircrushin3 小时前
一拍即传的平替,完全免费的实时照片墙!
前端
鹏北海5 小时前
JSBridge 原理详解
前端
孟健5 小时前
我的网站被黑了:一天灌入 227 万条垃圾数据,AI 写的代码差点让我社死
前端
anOnion6 小时前
构建无障碍组件之Checkbox pattern
前端·html·交互设计
IT枫斗者7 小时前
IntelliJ IDEA 2025.3史诗级更新:统一发行版+Spring Boot 4支持,这更新太香了!
java·开发语言·前端·javascript·spring boot·后端·intellij-idea
N***p3657 小时前
Spring Boot项目接收前端参数的11种方式
前端·spring boot·后端
NGC_66118 小时前
二分查找算法
java·javascript·算法
享誉霸王9 小时前
15、告别混乱!Vue3复杂项目的规范搭建与基础库封装实战
前端·javascript·vue.js·前端框架·json·firefox·html5