Detailed steps for Vue2 and Vue3 to implement global automatic registration of components

In the development of Vue projects, frequently registered components, whether they are public components or basic components, need to be frequently referenced by import in the component if they want to use them in other components. Is there a way to achieve global automation of components? register?
Answer: yes

1. Relevant knowledge points

Knowledge points: require.context, forEach, replace

2. Implementation method (main.js)

For the specific implementation method, please refer to the implementation method of Vue official website component registration , and make a second improvement modification

1、View 2:

//全局自动注册组件
const requireComponent = require.context(
  '@/components/',
  true,
  /.vue/
);
requireComponent.keys().forEach(fileName => {
    
    
  const componentConfig = requireComponent(fileName);
  const componentName = fileName.replace(/(\.\/|\.vue)/g, '').replace(new RegExp('/','g'),"");
  // 全局注册组件
  Vue.component(
    componentName,
    // 如果这个组件选项是通过 `export default` 导出的,
    // 那么就会优先使用 `.default`,否则回退到使用模块的根。
    componentConfig.default || componentConfig
  );
  console.log('全局注册组件',componentName)
});

2、View 3:

//全局自动注册组件
const requireComponent = require.context(
    '@/',
    true,
    /.vue/
);
const app = createApp(App)
requireComponent.keys().forEach(fileName => {
    
    
    const componentConfig = requireComponent(fileName);
    const componentName = fileName.replace(/(\.\/|\.vue)/g, '').replace(new RegExp('/', 'g'), "");
    // 全局注册组件
    app.component(
        componentName,
        // 如果这个组件选项是通过 `export default` 导出的,
        // 那么就会优先使用 `.default`,否则回退到使用模块的根。
        componentConfig.default || componentConfig
    );
    console.log('全局注册组件', componentName)
});

If you feel that the writing is good, comments and discussions are welcome. This article is original. If you need to reprint, please indicate the source;

Guess you like

Origin blog.csdn.net/qq_36034945/article/details/123007984