使用情景
在项目开发过程中,通常把需要重复使用的组件放在components文件下作为公共组件。一般使用方式是,在需要使用的组件中引入公共组件,然后再注册、使用。这种方式,在公共组件使用较多的情况下显得比较繁琐。所以,为了提高开发效率,把components文件夹下面的这些公共组件直接注册为全局组件。在使用时无需引入注册,直接使用。
使用方式:
1.在src目录下创建lib/globals.js;
2.在main.js中引入该文件
// Globally register all base components for convenience, because they
// will be used very frequently. Components are registered using the
// PascalCased version of their file name.
import Vue from 'vue'
import upperFirst from 'lodash/upperFirst'
import camelCase from 'lodash/camelCase'
// https://webpack.js.org/guides/dependency-management/#require-context
const requireComponent = require.context(
// Look for files in the current directory
'../components',
// Do not look in subdirectories
true,
// Only include "_base-" prefixed .vue files
/[\w-]+\.vue$/
)
// For each matching file name...
requireComponent.keys().forEach((fileName) => {
// Get the component config
const componentConfig = requireComponent(fileName)
// Get the PascalCase version of the component name
const componentName = upperFirst(
camelCase(
fileName
// Remove the "./_" from the beginning
.replace(/^\.\/_/, '')
// Remove the file extension from the end
.replace(/\.\w+$/, '')
)
)
// console.log(componentName)
// Globally register the component
Vue.component(componentName, componentConfig.default || componentConfig)
})