Global automation components registration

The official address
during use vue build the project, we will set some common components, he may only contain a button or other of a small feature, but we are frequently called in different components of the page. At this time, if each component pages are referenced, there will be a lot of duplication jumbled code, you can change the global registration. details as follows:

  1. These common base assembly is placed in the same folder: The components / baseComponents /
  2. Application of global import file entry (eg: main.js), the following sample code is the official, was modified slightly:
// 全局导入组件
const requireComponent = require.context(
  // 其组件目录的相对路径
  './components/baseComponents',     
  // 是否查询其子目录
  false,                      
  // 匹配基础组件文件名的正则表达式, 这里可以匹配的文件名为BaseXxxx.vue格式
  /Base[A-Z]\w+\.(vue|js)$/   
)
 
requireComponent.keys().forEach(fileName => {
  // 获取组件配置
  const componentConfig = requireComponent(fileName)
 
  // 获取组件的 PascalCase 命名
  const componentName = upperFirst(
    camelCase(
      // 剥去文件名开头的 `'./` 和结尾的扩展名
      fileName.replace(/^\.\/(.*)\.\w+$/, '$1')
    )
  )
 

// global registration component

  Vue.component(
    componentName,
    // 如果这个组件选项是通过 `export default` 导出的,
    // 那么就会优先使用 `.default`,否则回退到使用模块的根。
     componentConfig.default || componentConfig
  )
})

Note: The above code must be placed before the new Vue ().
3. Use a good global components directly registered in the corresponding components of the page:

<base-xxxx :title="'自动化全局注册基础组件'"></base-xxxx>

Example: // automatically registered global components, such as a page directly:

const requireCom = require.context(
  './components',
  false,
  /Mei\w+\.(vue)$|\w+\.(js)/
)
requireCom.keys().forEach(fileName => {
  const comConfig = requireCom(fileName)
  const comName = upperFirst(
    camelCase(
      // 剥去文件名开头的 `./` 和结尾的扩展名
      fileName.replace(/^\.\/(.*)\.\w+$/, '$1')
    )
  )
  Vue.component(comName, comConfig.default || comConfig)
})
Published 128 original articles · won praise 3 · Views 2556

Guess you like

Origin blog.csdn.net/qq_26642611/article/details/104428671