自定义Vue3Loading插件

Loading.ts

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
import type { App, VNode } from 'vue'

import Loading from './index.vue'

//通过createVNode转成Vnode
import { createVNode, render } from '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,
}
console.log(app, Vnode.component?.exposed);
}
}

Loading.vue

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
<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>

main.ts

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
import Loading from './components/Loading/index'

app.use(Loading)

type Lod = {
show: () => void,
hide: () => void,
}

//编写ts loading 声明文件放置报错 和 智能提示
declare module "vue" {
export interface ComponentCustomProperties {
_loading: Lod
}
}