vue3 批量注册全局组件(共用组件)

作者: 简小咖 | 来源:发表于2022-07-07 16:34 被阅读0次

    vue2中引入共用组件

    \\ components/index.js
    import Vue from 'vue'
    import LayoutContent from './layout/LayoutContent'
    import FormPart from './form-part'
    Vue.component(LayoutContent.name, LayoutContent)
    Vue.component(FormPart.name, FormPart)
    

    main.js 中引入

    import './components'
    

    就可以了!

    vue3中引入共用组件

    \\ components/index.js
    import FormPart from './form-part/index.vue'
    import LayoutContent from "./layout/LayoutContent.vue";
    
    export default {
      install(app) {
        app.component(FormPart.name, FormPart);
        app.component(LayoutContent.name, LayoutContent);
      },
    };
    

    main.js 中引入

    import  Components from '@/components'
    const app = createApp(App)
    app.use(Components)
    app.mount('#app')
    

    就可以了!

    批量注册

    vue2的时候

    /* Components */
    import Vue from 'vue'
    const components = require.context('./', true, /index\.vue$/);
    components.keys().forEach(key => {
      let component = components(key).default;
      Vue.component(component.name, component)
    })
    

    vue3 用vite不能使用require.context,要使用import.meta.globEage

    /* Components */
    const components= import.meta.globEager('./*/index.vue')
    export default {
      install(app) {
        Object.keys(components).forEach(key => {
        let component = components[key].default
        app.component(component.name, component)
      })
      },
    };
    
    

    相关文章

      网友评论

        本文标题:vue3 批量注册全局组件(共用组件)

        本文链接:https://www.haomeiwen.com/subject/ucjpbrtx.html