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



我关注了 Vuejs 网站上的文档,学习如何全局注册 vue 组件。

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

我还控制台记录了组件键以查看是否包含任何 vue 组件,但它只返回了全局(根)文件夹中的组件。

https://v2.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
)
})

以下是我最终为达到相同结果而写的内容:

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
)
})

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

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

/src 主.js/全球

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

<ProgressBar></ProgressBar>

@Anson C

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)$/
)

此代码完全按预期工作。意味着它将按预期返回子文件夹中的所有文件(例如./Base/BaseInput.vue将返回BaseInput)。但是要导入这些文件,您还必须添加相应的路径。

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

这只会导入./BaseInput它应该./Base/BaseInput的不准确路径。

那里有:

// Get PascalCase name of component
const componentName = Vue._.upperFirst(
Vue._.camelCase(
fileName
.split('/')
.pop()
.replace(/.w+$/, '')
)
)

此代码返回文件和文件夹的完美路径。

最新更新