从vue2升级到vue3的改变之路前端学习笔记前端Vue专辑

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

2022-07-07  本文已影响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)
  })
  },
};

上一篇下一篇

猜你喜欢

热点阅读