vue3自定义全局组件(插件)

628 阅读1分钟
  1. 做一个全局的loading插件(组件)
  2. components/Loading/index.ts
import type {App,VNode} from 'vue'
import Loading from './index.vue'
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
    }
  }
}

3.components/Loading/index.vue

<!-- loading插件 -->
<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({
  isShow,
  show,
  hide
})
</script>
<template>
<div v-if="isShow" class='loading'>
  loading.....
</div>
</template>

<style lang='scss' scoped>
.loading {
  background: black;
  opacity: 0.8;
  font-size: 30px;
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
  width: 100vw;
  color: white;
}
</style>

4.main.ts注册

import Loading from './components/Loading'
// 做一个下类型声明
type Lod = {
  show: () => void,
  hide: () => void
}
declare module '@vue/runtime-core' {
  export interface ComponentCustomProperties {
    $loading: Lod
  }
}
// 注册
app.use(Loading)

5.全局组件中使用

<!--  -->
<script setup lang='ts'>
import {ref,reactive,getCurrentInstance} from 'vue'

const instance = getCurrentInstance()
instance?.proxy?.$loading.show()
setTimeout(() => {
instance?.proxy?.$loading.hide()
},5000)

</script>
<template>
<div class=''>
  {{ $filters.format('苹果手机') }}
  使用自定义组件显示出一个loading
</div>
</template>

<style lang='scss' scoped>

</style>