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>

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值