实例: 自定义全局loading
js
//component/Loading/index.ts
import { createVNode, render } from "vue";
import type { App, VNode } from "vue";
import Loading from "./index.vue";
//声明类型
type Load = {
show: () => void;
hide: () => void;
};
//定义声明文件
declare module "@vue/runtime-core" {
export interface ComponentCustomProperties {
$loading: Load;
}
}
export default {
install(app: App) {
//app实例
const Vnode: VNode = createVNode(Loading); // 转为VNode
render(Vnode, document.body); //手动挂载到body上
//Vnode.component?.exposed 获取 defineExpose 抛出的东西
app.config.globalProperties.$loading = {
//挂载到全局里
show: Vnode.component?.exposed?.show,
hide: Vnode.component?.exposed?.hide,
};
},
};html
<script setup lang='ts'>
import { ref, reactive } from 'vue'
const isShow = ref<Boolean>(false)
const show = () => isShow.value = true
const hide = () => isShow.value = false
defineExpose({
show, hide
})
</script>
<template>
<div v-if="isShow" class="loading">
Loading...
</div>
</template>
<style scoped>
.loading {
background-color: black;
opacity: 0.8;
font-size: 30px;
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
width: 100vh;
top: 0;
left: 0;
position: fixed;
color: white;
}
</style>typescript
import Loading from './components/Loading/index'
app.use(Loading)