Vue3_30(編寫Vue3插件)

插件

插件是自包含的代碼,通常向 Vue 添加全局級功能。你如果是一個對象需要有install方法Vue會幫你自動注入到install 方法 你如果是function 就直接當install 方法去使用

使用插件

在使用 createApp() 初始化 Vue 應(yīng)用程序后,你可以通過調(diào)用 use() 方法將插件添加到你的應(yīng)用程序中。

實現(xiàn)一個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 的開關(guān)
 
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提供的底層方法 可以給我們組件創(chuàng)建一個虛擬DOM 也就是Vnode
        const vnode: VNode = createVNode(Loading)
        //render 把我們的Vnode 生成真實DOM 并且掛載到指定節(jié)點
        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')
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容