ts
// main.ts
import { createApp } from 'vue'
import App from './App.vue'
import Loading from "./components/Loading/index.ts";
const app = createApp(App)
type Lod = {
show: () => void,
hide: () => void
}
//编写ts loading 声明文件放置报错 和 智能提示
declare module '@vue/runtime-core' {
export interface ComponentCustomProperties {
$loading: Lod
}
}
app.use(Loading)
app.mount('#app')
js
<template>
<!-- App.vue-->
<div>
<img id="img" width="400" height="400" src="./assets/unnamed.jpg" alt=""/>
</div>
</template>
<script setup lang="ts">
import {getCurrentInstance} from "vue";
const instance = getCurrentInstance()
instance?.proxy?.$loading.show()
setTimeout(() => {
instance?.proxy?.$loading.hide()
}, 5000)
</script>
<style>
</style>
ts
// /components/Loading/index.ts
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,
}
}
}
js
<template>
<!-- components/Loading/index.vue-->
<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>