Vue自動化注冊全局組件腳本


今天有一個idea,vue一些組件,可能會全局都用到,我覺得在main.js寫

Vue.component(name, instance)

然后很命令式,寫着也不好看,想着能夠有一個函數可以指定加載比如components下的文件,自動完成全局化注冊,想起來就很帥

放代碼:

export function autoLoadingGlobalComponent() {
  const requireComponent = require.context(
    // 其組件目錄的相對路徑
    '../components',
    // 是否查詢其子目錄
    false,
    // 匹配vue后綴文件名的文件
    /\.vue$/
  )
  // 遍歷獲取到的文件名,依次進行全局注冊
  requireComponent.keys().forEach(fileName => {
    // 獲取組件配置(實例)
    const componentConfig = requireComponent(fileName)
    // 獲取組件的 PascalCase 命名(eg: MYHeader)
    const componentName = _.upperFirst(
      // 獲取駝峰式命名
      _.camelCase(
        // 剝去文件名開頭的 `./` 和結尾的擴展名 eg: ./food-header.vue -> foodHeader
        fileName.replace(/^\.\/(.*)\.\w+$/, '$1')
      )
    )
      // 全局注冊組件
    Vue.component(
      componentName,
      // 如果這個組件選項是通過 `export default` 導出的,
      // 那么就會優先使用 `.default`,
      // 否則回退到使用模塊的根。
      componentConfig.default || componentConfig
    )
  })
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM