定义一个全局加载组件
一、首先定义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>