vue3-自定义插件

96 阅读1分钟

1.怎么做

index.ts
// 1.注册插件支持的两种形式: 对象或者函数形式,由于使用形式为
const app = createApp()
app.use(插件名称) // use会注册组件:
//要使得组件能够挂载到全局,所以我们必须传入app作为install方法的参数

// 2.编写intall方法
import type {App, VNode} from 'vue'
import Loading from './index.vue' // 只是个例子
import {createVNode, render} from 'vue'
export default {
    install(app: App) {
        // 创建组件的虚拟dom
        const Vnode : VNode = createVNode(Loading)
        // 创建虚拟dom到body
        render(Vnode, document.body)
        // 挂载全局属性到指定变量上 利用exposed读取到当前组件内部的api、变量
        app.config.globalProperties.$loading = {
            show: Vnode.component?.exposed?.show,
            hide: Vnode.component?.exposed?.hide
        }
        console.log(app, 1233, Vnode)
    }
}

// 3.注册组件
app.use(Loading)

// 4.调用组件方法
instance?.proxy?.$loading.show()

// 5.抵用$loading 红线报错处理
//5.1定义组件内方法
type Lod = {
    show: ()=>void,
    hide: ()=>void
}
// 5.2声明文件
declare module '@vue/runtime-core'{
    export interface ComponentCustomProperties {
        $loading: Lod
    }
}

2.作用

面试常考题
编写常用插件

3.拓展

// 实现use函数
import type {App} from 'vue'
import app from './main'
type plugin {
    install: (app: App, ...options:any[])=> void //options为用户自定义配置项
}
// use函数 内部调用组件的install方法,并且会自动过滤掉已经添加过的组件,而且支持链式调用
// (1)use函数需要限制传入的组件有install方法
// (2)用new Set去过滤
// (3)需要返回对应挂载对象app,让用户能够不断调用use函数
const addedList = new Set()

app.MyUse = function MyUse<T>(plugin:T):T{
    if (addedList.has(plugin)){
       console.error('该组件已添加,请不要重复注册')
       return
    } 
    
    if (typeof plugin === 'function'){
     plugin(app, ...options)
    } else {
    plugin.install(app,...options)
    }
    addedList.add(plugin)
   
   return app
    
}