Vue “once and for all” component registration


Usually, before components are used, they need to be imported and then registered. However, if there are many high-frequency components, doing so every time will not only add a lot of code, but also be inefficient! How should we optimize it?

In fact, we can use webpack’s require Context () method to create its own (module) context, so as to realize the automatic and dynamic require component.

First, we add a file called global.js in the components folder (which contains high-frequency components). In this file, we use require.context to dynamically package all the required high-frequency components

import Vue from 'vue'

function capitalizeFirstLetter(string) {
  return string.charAt(0).toUpperCase() + string.slice(1)

const requireComponent = require.context(
  '.', false, /\.vue$/
   //Find the components folder and click Vue named file

requireComponent.keys().forEach(fileName => {
  const componentConfig = requireComponent(fileName)

  const componentName = capitalizeFirstLetter(
    fileName.replace(/^\.\//, '').replace(/\.\w+$/, '')
    //Because the format of the obtained filename is: '/ dataList. Vue ', so here we go back and forth and only keep the real file name

  Vue.component(componentName, componentConfig.default || componentConfig)

Then in main JS file JS file



Finally, we can use these high-frequency components in the page anytime and anywhere without introducing them one by one manually.

Recommended Today

Redis featured Q & A

Redis data type type brief introduction characteristic scene String (string) Binary security It can contain any data, such as JPG pictures or serialized objects. One key can store up to 512M It can be used to do the simplest data. It can cache a simple string or a JSON format string. The implementation of redis […]