vue3+ts自定义插件
使用:
<template lang="html">
<div></div>
</template>
<script lang="ts" setup>
import { ref, reactive, getCurrentInstance } from "vue";
const instance = getCurrentInstance();
console.log(instance?.proxy, "instance?.proxy?");
instance?.proxy?._loading.show();
setTimeout(() => {
instance?.proxy?._loading.hide();
}, 5000);
</script>
<style lang="scss"></style>
全局组件:
loading/index.ts
import { createVNode,VNode,render, type App } from "vue";
import Loading from "./index.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,'222',Vnode.component?.exposed)
}
}
loading/index.vue
<template>
<div v-if="isShow" class="loading">loading...</div>
</template>
<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({
hide,
show,
isShow,
});
</script>
<style>
.loading {
background: black;
opacity: 0.8;
font-size: 30px;
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
color: white;
position: absolute;
width: 100vw;
}
</style>
在main.ts中控制
import Loading from "./components/loading";
export const app = createApp(App);
import { myUse } from "./myUse";
myUse(Loading)
// app.use(Loading);
//不提示可以设置属性
type Lod = {
show: () => void,
hide:()=>void
}
declare module "@vue/runtime-core" {
export interface ComponentCustomProperties{
_loading:Lod
}
}
myUser.ts
import { App } from "vue";
import {app} from "./main"
interface Use{
install:(app:App,...options:any[])=>void
}
const installList = new Set();
export function myUse<T extends Use>(plugin: T, ...options: any[]) {
if (installList.has(plugin)) {
console.error("注册过了",plugin)
} else {
plugin.install(app,...options);
installList.add(plugin)
}
}