插件注册组件(用于编写组件库)

在src下创建一个globalComponents文件,文件内建一个index.ts
在这里插入图片描述

index.ts中内容(注意:组件中的name要给内容)
import Child from '@/components/child.vue'  //把所有要注册的组件引入
import {
    
     App, Component } from "vue"

//定义接口,其中有一个install的方法
interface GlobalComponents {
    
    
    install: (app: App) => void
}

//定义数组,装所有引进来的组件
const componentsArr: Component[] = []  //类型为vue中引入的Component的数组 先初始化为一个空数组
componentsArr.push(Child) //吧要注册的组件push进去


const aicomponents: GlobalComponents ={
    
    
    install(app){
    
    
        componentsArr.map((item:Component)=>{
    
      //循环注册组件
            app.component(item.name!,item)
        })
    }
}
export default aicomponents //导出
main.ts中
import aicomponents from '@/globalComponents/index';

app.use(aicomponents)
html中使用
<child></child>

在这里插入图片描述

定义接口时键和值都是string时

猜你喜欢

转载自blog.csdn.net/weixin_49866029/article/details/108816189