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)