During the development of the project, we often try to encapsulate some of the more common global components, but every time we add a component, we need to manually introduce the registration in main.js, which is not only troublesome, but also a lot of code, which is really annoying. So simply encapsulate an automated registration global component.

  1. Customize the global component folder

Create a new globalComponents under SRC to hold globalComponents and create a new component, such as Orange.

  1. Components automatically register configuration files

Create an index.js in globalComponents to find all components and automatically register them

// Automatically registers global components and must be recompiled each time a new component is added
import Vue from 'vue'

const requireComponent = require.context(
  '.. /globalComponents'.// The relative path of its component directory
  true.// Whether to query the subdirectory
  /\.vue$/ // A regular expression that matches the underlying component file name
)
requireComponent.keys().forEach(fileName= > {
  const componentConfig = requireComponent(fileName); // Get the component configuration
  /** * compatible with import export and require module.export */
  // If the component option is exported via export default,.default is preferred
  const comp = componentConfig.default || componentConfig; 
  Vue.component(comp.name, comp) // Name is the name defined by the component property
})
Copy the code
  1. Edit the Orange/index. Vue

The most important component is the name defined by the component property (name is the automatically registered component name)

<template>
  <div class="wrapper">
    Orange
  </div>
</template>

<script>
export default {
  name: 'Orange'.// The name attribute value will be the component name used later 
        , which must be unique
  components: {},
  props: {},
  data() {
    return{}},created() {},
  mounted() {},
  methods: {}}</script>
Copy the code
  1. File. The main entrance of js import globalComponents/index. Js
// main.js

import Vue from 'vue'
// Automatically register global components
import './globalComponents/index.js'
Copy the code
  • After completing the steps above, you can use the global component directly
  • Usage:
<template>
  <div class="wrapper">
    <! -- Auto-register global component -->
    <orange />
  </div>
</template>
Copy the code