如何定义封装全局组件

这里以封装的svg组件为例

在src文件夹目录下创建一个index.ts文件:用于注册components文件夹内部全部全局组件!!!

import SvgIcon from './SvgIcon/index.vue';
import type { App, Component } from 'vue';
const components: { [name: string]: Component } = { SvgIcon };
export default {
    install(app: App) {
        Object.keys(components).forEach((key: string) => {
            app.component(key, components[key]);
        })
    }
}

在入口文件引入src/index.ts文件,通过app.use方法安装自定义插件

import gloablComponent from './components/index';
app.use(gloablComponent);
//当执行use方法时就会去指定引入的ts文件中暴露出来的install方法,这个方法会把这里的app对象传递过去,那么注册全局组件就可以通过app.component(组件名, 具体的组件来实现);以后我们有新的全局组件只需要在这个index.ts文件中,引入对应的组件,加入对应的components对象中即可

 

你可能感兴趣的:(web,前端,javascript,开发语言)