Vue3 插件实现

Vue3 插件实现

编写Loading插件并导出方法

<template>
  <div v-if="isShow" class="loading">Loding...</div>
</template>

<script setup lang="ts">
import { ref } from "vue"

const isShow = ref<boolean>(false)

const show = () => (isShow.value = true)
const hide = () => (isShow.value = false)

defineExpose({
  isShow,
  show,
  hide,
})
</script>

<style scoped>
.loading {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: rgba(0, 0, 0, 0.5);
  color: #fff;
  text-align: center;
  line-height: 100vh;
  z-index: 999;
}
</style>

编写插件方法

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,
    }
    console.log("app", app, Vnode)
  },
}

导入app

import Loading from "./components/Loading"

export const app = createApp(App)
app.use(Loading)

//防止类型报错
declare module "vue" {
  export interface ComponentCustomProperties {
    $Loading: {
      show: () => void
      hide: () => void
    }
  }
}

插件使用

import { getCurrentInstance } from "vue"

const instance = getCurrentInstance()
instance?.proxy?.$Loading.show()