Before using a component, import it and then register it:
import BaseButton from './baseButton'
import BaseIcon from './baseIcon'
import BaseInput from './baseInput'
export default {
components: {
BaseButton,
BaseIcon,
BaseInput
}
Copy the code
But if you have a lot of components, each time you have to import each component you want to use, and then register the components, you can add a lot of code
At this point, we need to use webpack’s require.context() method to create our own (module) context to implement the automatic dynamic require component. This method takes three parameters: the folder directory to search, whether its subdirectories should also be searched, and a regular expression to match the files.
We’ll start by adding a file called global.js to the Components folder (which contains high-frequency components) and using require.context to dynamically package all high-frequency components we need. Then import the global.js file in the main.js file.
// global.js import Vue from 'Vue' function changeStr (STR) {return str.charat (0).toupperCase () + str.slice(1)} const requireComponent = require.context('./', false, /.vue$/) // Find components ending in vue in the same directory const install = () => {requireComponent.keys().foreach (fileName => {let config = RequireComponent (fileName) console.log(config) //./child1.vue let componentName = changeStr( fileName.replace(/^.//, '').replace(/.\w+$/, '') ) Vue.component(componentName, Config. The default | | config)})} export default {install / / exposed outside the install method}Copy the code
// main.js
import index from './components/global.js'
Vue.use(index)
Copy the code
This allows you to use these high-frequency components anywhere in the page, rather than manually importing them one by one.