vue 批量注册组件

目的:批量注册组件,挂载一次终身使用

1. components/index.js 中批量注册组件

  • 组件必须有 name 属性
export default {
    install(Vue) {
	// 1- 声明组件
        // require.context('路径', 是否深入查找, 正则选出需要注册的组件)
        const requireComponent = require.context('./', true, /\.vue$/)
        /*[
	    0: "./Breadcrumb/index.vue"
	    1: "./Hamburger/index.vue"
	    2: "./PageTools/index.vue"
        ]*/
        
        // 2- 遍历注册
        requireComponent.keys().forEach((item) => {
            //  获取组件对象  requireComponent(item).default
            //  组件对象
            const moduleObj = requireComponent(item).default
            /*{
                "name": "Breadcrumb",
                "watch": {},
                "methods": {},
                "staticRenderFns": [],
                "_compiled": true,
                "_scopeId": "data-v-b50ef614",
                "beforeCreate": [
                    null
                ],
                "beforeDestroy": [
                    null
                ],
                "__file": "src/components/Breadcrumb/index.vue",
                "_Ctor": {}
            }*/
            Vue.component(moduleObj.name, moduleObj)
        }) 
    }
}

2. main.js 中使用组件

// 导入组件
import plugins from '@/components/index'
// 使用组件
Vue.use(plugins)
posted @ 2022-04-02 21:11  嗤嗤13  阅读(280)  评论(0)    收藏  举报