loading.vue
<template>
<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>
loading.ts
import { createVNode, render, VNode, App } from 'vue';
import Loading from './loading.vue'
export default {
install(app: App) {
const vnode: VNode = createVNode(Loading)
render(vnode, document.body)s
app.config.globalProperties.$Loading = {
show: () => vnode.component?.exposed?.show(),
hide: () => vnode.component?.exposed?.hide()
}
}
}
main.ts
import Loading from ‘./loading.js’
app.use(Loading)
// 需要加声明,否则会报错(vite-env.d.ts)
///
declare module '*.vue' {
import type { DefineComponent } from 'vue'
const component: DefineComponent<{}, {}, any>
export default component
declare module '@vue/runtime-core' {
export interface ComponentCustomProperties {
$Loading: Lod
}
}
}