vue3插件编写

目录文件

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()
}
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容