在子文件夹中的 Vuejs 中全局注册组件

Ans*_*n C 4 javascript webpack vue.js nuxt.js

我已经按照 Vuejs 网站上的文档学习了如何全局注册 vue 组件。

我已经定义了组件文件夹的相对路径./global并设置为在子文件夹中查找true(默认为 false)。但是,它仍然不会查看子文件夹。

我还对组件键进行了 console.logged 以查看是否包含任何 vue 组件,但它只返回全局(根)文件夹中的组件。

https://vuejs.org/v2/guide/components-registration.html

import Vue from 'vue'
import upperFirst from 'lodash/upperFirst'
import camelCase from 'lodash/camelCase'

const requireComponent = require.context(
  // The relative path of the components folder
  './global',
  // Whether or not to look in subfolders
  true,
  // The regular expression used to match base component filenames
  /[A-Z]\w+\.(vue|js)$/
)

console.log(requireComponent.keys())

requireComponent.keys().forEach(fileName => {
  // Get component config
  const componentConfig = requireComponent(fileName)

  // Get PascalCase name of component
  const componentName = upperFirst(
    camelCase(
      // Strip the leading `./` and extension from the filename
      fileName.replace(/^\.\/(.*)\.\w+$/, '$1')
    )
  )

  // Register component globally
  Vue.component(
    componentName,
    // Look for the component options on `.default`, which will
    // exist if the component was exported with `export default`,
    // otherwise fall back to module's root.
    componentConfig.default || componentConfig
  )
})
Run Code Online (Sandbox Code Playgroud)

Tim*_*rom 5

这是我最终为了达到同样的结果而写的:

const requireComponent = require.context(
  // The relative path of the components folder
  './global',
  // Whether or not to look in subfolders
  true,
  // The regular expression used to match base component filenames
  /[A-Z]\w+\.(vue|js)$/
)

requireComponent.keys().forEach(fileName => {
  // Get component config
  const componentConfig = requireComponent(fileName)
  // Get PascalCase name of component
  const componentName = Vue._.upperFirst(
    Vue._.camelCase(
      fileName
        .split('/')
        .pop()
        .replace(/\.\w+$/, '')
    )
  )

  // Register component globally
  Vue.component(
    componentName,
    // Look for the component options on `.default`, which will
    // exist if the component was exported with `export default`,
    // otherwise fall back to module's root.
    componentConfig.default || componentConfig
  )
})
Run Code Online (Sandbox Code Playgroud)

确保 global 中的所有文件都大写并具有 .vue 或 .js 扩展名。

此外,使用您提供的路径,请确保 main.js(或任何您的引导程序文件被调用)位于全局变量的一个目录中。例子:

/src main.js /全局

这将使诸如 ProgressBar.vue 之类的文件在所有组件中作为 ProgressBar 全局可用

<ProgressBar></ProgressBar>
Run Code Online (Sandbox Code Playgroud)