目录文件
index.ts文件
import type { App, VNode } from 'vue'
import Loading from "./index.vue";
import { createVNode, render } from 'vue'
// vue.use 会调用 install 函数
export default {
install(app: App) {
console.log('app', app);
const vNode: VNode = createVNode(Loading) // 先把组件转成VNode
render(vNode, document.body) // 通过render 函数挂载到 document.body 下
const _exposed = vNode.component?.exposed
app.config.globalProperties.$Loing = { // 全局挂载到 globalProperties 下
show: _exposed?.show,
hide: _exposed?.hide,
}
}
}
index.vue
<template>
<div v-show="showLoading" class="loading">加载中...</div>
</template>
<script lang='ts' setup>
const showLoading = ref(false)
const show = () => {
showLoading.value = true
}
const hide = () => {
showLoading.value = false
}
defineExpose({show, hide})
</script>
<style scoped>
.loading {
background-color: rgba(0, 0, 0, .9);
position: fixed;
top: 0;
left: 0;
right: 0;
bottom: 0;
display: flex;
justify-content: center;
align-items: center;
color: #ddd;
}
</style>
main.ts文件
import Loading from '@/components/Loading'
app.use(Loading)
type Loing = {
show: () => void
hide: () => void
}
// 声明文件扩展 固定写法
declare module '@vue/runtime-core' {
export interface ComponentCustomProperties {
$Loing: Loing
}
}
app.mount('#app')
组件里面应用
const instance = getCurrentInstance()
console.log('instance', instance)
const test = () => {
instance?.proxy?.$Loing.show()
}
网友评论