vue 中如何全局注册组件

此内容为 为vue中 使用 正则 找到某个目录下所有的 组件,并注册到全局,不需要手动在main 中进行引入全局

1、创建注册全局组件的js 文件

// 导入所有与library 同级的vue 组件
const importFn = require.context('./', false, /\.vue$/)

export default {
    install(app) {
        // 循环遍历每个vue组件的路径
        console.log(importFn);
        importFn.keys().forEach(key => {
            // 通过路径获得每个vue 组件
            const component = importFn(key).default
            // 注册
            app.component(component.name, component)
        })
    }
}

此时我们的文件结构是这样的,作为参考。我们需要将 library中的 两个vue 组件进行全局注册

 2、在main中进行使用

// 全局组件
import ui from '@/components/library'

// 使用use 使用
createApp(App).use(store).use(vant).use(ui).mount('#app')

猜你喜欢

转载自blog.csdn.net/Kerwin__li/article/details/128827426
今日推荐