插件
插件是自包含的代码,通常向 Vue 添加全局级功能。你如果是一个对象需要有install方法Vue会帮你自动注入到install 方法 你如果是function 就直接当install 方法去使用
使用插件
在使用 createApp() 初始化 Vue 应用程序后,你可以通过调用 use() 方法将插件添加到你的应用程序中。
实现一个Loading
Loading.Vue
<template><div v-if="isShow" class="loading"><div class="loading-content">Loading...</div></div></template><script setup lang='ts'>import { ref } from 'vue';const isShow = ref(false)//定位loading 的开关const show = () => {isShow.value = true}const hide = () => {isShow.value = false}//对外暴露 当前组件的属性和方法defineExpose({isShow,show,hide})</script><style scoped lang="less">.loading {position: fixed;inset: 0;background: rgba(0, 0, 0, 0.8);display: flex;justify-content: center;align-items: center;&-content {font-size: 30px;color: #fff;}}</style>
Loading.ts
import { createVNode, render, VNode, App } from 'vue';import Loading from './index.vue'export default {install(app: App) {//createVNode vue提供的底层方法 可以给我们组件创建一个虚拟DOM 也就是Vnodeconst vnode: VNode = createVNode(Loading)//render 把我们的Vnode 生成真实DOM 并且挂载到指定节点render(vnode, document.body)// Vue 提供的全局配置 可以自定义app.config.globalProperties.$loading = {show: () => vnode.component?.exposed?.show(),hide: () => vnode.component?.exposed?.hide()}}}
Main.ts
import Loading from './components/loading'let app = createApp(App)app.use(Loading)type Lod = {show: () => void,hide: () => void}//编写ts loading 声明文件放置报错 和 智能提示declare module '@vue/runtime-core' {export interface ComponentCustomProperties {$loading: Lod}}app.mount('#app')
————————————————
版权声明:本文为CSDN博主「小满zs」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/qq1195566313/article/details/123300264
