插件是自包含的代码,通常向 Vue 添加全局级功能。你如果是一个对象必须要有install方法Vue会帮你自动注入app到install方法,你如果是function就直接当install方法去使用。
使用插件
在使用 createApp() 初始化 Vue 应用程序后,你可以通过调用 use() 方法将插件添加到你的应用程序中。
// main.ts
import {createApp} from 'vue'
import App from './App.vue'
// 引入插件
import loading from "./plugin/loading/index";
// 创建App实例
const app = createApp(App)
// 注册插件
app.use(loading)
// 挂载
app.mount('#app')
书写插件 实现一个loading插件
1.Login.vue
<!--Login.vue-->
<template>
<div v-if="isShow" class="loading">
<div class="loading-content">Loading...</div>
</div>
</template>
<script setup lang='ts'>
import {ref} from 'vue';
// loading 的开关
const isShow = ref(false)
// 显示
const show = () => {
isShow.value = true
}
// 隐藏
const hide = () => {
isShow.value = false
}
//对外暴露 当前组件的属性和方法
defineExpose({
isShow,
show,
hide
})
</script>
<style scoped lang="scss">
.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>
2.Login.ts
// Login.ts
import {App, createVNode, render, VNode} from 'vue';
import Loading from './index.vue'
export default {
install(app: App) {
// createVNode vue提供的底层方法 可以把我们组件创建为虚拟DOM 也就是Vnode
const 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 {createApp} from 'vue'
import App from './App.vue'
// 引入插件
import loading from "./plugin/loading/index";
// 创建App实例
const app = createApp(App)
// 注册插件
app.use(loading)
// 挂载
app.mount('#app')
3.编写Ts声明文件
// 书写在main.ts中
declare module '@vue/runtime-core' {
export interface ComponentCustomProperties {
$loading: {
show: () => void,
hide: () => void,
}
}
}
4.使用插件
<!--任意组件-->
<template>
<!--显示loading按钮-->
<button @click="showLoading">显示loading</button>
</template>
<script setup lang="ts">
import {ComponentInternalInstance, getCurrentInstance} from "vue";
// 获取组件实例
const {appContext} = getCurrentInstance() as ComponentInternalInstance
// 显示login的方法
const showLoading = () => {
// 显示loading
appContext.config.globalProperties.$loading.show()
// 2秒后消失
setTimeout(appContext.config.globalProperties.$loading.hide, 2000)
}
</script>