Vue automatically introduces and registers components or routes in batches to achieve detailed explanation

Introduce components in batches with .vue suffix or .js, or .ts files

Sometimes there are a large number of components with the .vue suffix, or .js, or .ts files, and it is troublesome to manually introduce them one by one. Then you can try to create an index.js like this

This project uses vue3.x, vue2.x can also be used;

Here an idnex.js file is created in components

require.context reads files

The first parameter refers to the current folder, the second parameter is whether to recursively traverse to find child nodes and set it to true, and the third regular match

//自动注册,不必一个个导入导出
const requireComponent = require.context(
  // 其组件目录的相对路径
  './',
  // 是否查询其子目录,递归查询
  true,
  // 匹配基础组件文件名的正则表达式
  /.(vue)$/
)
var fileArr:any[] = [] //导出路由对象
requireComponent.keys().forEach((fileName) => {
  // 获取组件配置
  const componentConfig = requireComponent(fileName)
  let compName = fileName.split("/")[fileName.split("/").length - 1].split(".")[0];
  if (componentConfig.default) {
    fileArr.push({
        name: compName,
        compnent: componentConfig.default
    })
  }
})
export default fileArr;

 In this way, you will get an array. The objects of multiple components in the array have names and component contents. You can print the details yourself and try it out;

  

Referenced in main.ts

fileArr.forEach(item=>{
    console.log(item.name, item.compnent);
    vue.component(item.name, item.compnent);   //全局注册了
})

Traverse fileArr and register all components; this is a global registration, and you don’t need to import them one by one when using them. This approach can be used for small projects, but if too many files are globally registered for large projects, it may affect performance;

According to this idea, a large number of files such as routing, API, and status management are modularized and do not need to be imported manually. As long as you create this file, it will be automatically read;

Guess you like

Origin blog.csdn.net/qq_17189095/article/details/131811391