插件
插件是自包含的代碼,通常向 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')