vue3 插件开发
插件是向vue添加全局功能。你如果是一个对象需要提供install方法,你如果是function就直接当install 方法去使用。
写一个loading组件供全局使用:
1)目录结构
index.ts文件内容:
import { createVNode, render, App } from 'vue'
import Loading from './index.vue'
export default {
// 自定义组件需要install 函数
install(app:App) {
// 先转成虚拟dom
const vNode = createVNode(Loading)
render(vNode, document.body)
// vnode中通过exposed属性获取组件导出的方法
app.config.globalProperties.$loading = {
show: vNode.component?.exposed?.show,
hide: vNode.component?.exposed?.hide
}
console.log(vNode);
}
}
index.vue文件内容
<template>
<div v-if="showLoading">
loading...
</div>
</template>
<script setup>
let showLoading = ref(false)
const show = () => showLoading.value = true
const hide = () => showLoading.value = false
defineExpose({
show,
hide
})
</script>
<style scoped>
.loading {
position: absolute;
left: 0;
top: 0;
width: 100vw;
height: 100vh;
background-color: rgba($color: #000000, $alpha: .8);
color: #fff;
}
</style>
2) 在main.ts中引入
import loading from './components/loading' // 组件路径
//编写ts loading 声明文件放置报错 和 智能提示
type LoadingTypes = {
show: () => void,
hide: () => void
}
declare module '@vue/runtime-core' {
export interface ComponentCustomProperties {
$loading: LoadingTypes
}
}
app.use(loading)
3) 使用
import { getCurrentInstance} from 'vue'
const instance = getCurrentInstance()
instance?.proxy?.$Loading.show()
setTimeout(()=>{
instance?.proxy?.$Loading.hide()
},5000)