Purpose: Automatic batch registration of components.
General steps:
- use
require
Provided functionscontext
Loads all files in a directory.vue
File with suffix. - then
context
The function returns an import functionimportFn
- It has another property
keys()
Get all file paths
- It has another property
- Through the file path array, through the number array, and then use
importFn
Import component objects by path - Do global registration while traversing
Drop code:
src/components/library/index.js
// Extend vue's original functionality: global components, custom directives, mount prototype methods, note: no global filters. // Vue3.0 plugin: export an object, install function, pass in the default Vue constructor, Vue base extension // vue3.0 plugin: Export an object with the install function, which passes in the app instance by default, // import XtxSkeleton from './xtx-carousel. Vue '// import XtxCarousel from './xtx-carousel. Vue' // import XtxSkeleton from './xtx-carousel XtxMore from './xtx-more.vue' // import XtxBread from './xtx-bread.vue' // import XtxBreadItem from './xtx-bread-item.vue' // console.dir(importfn.keys ())) import defaultImg from '@/assets/images/200.png' // import all components in library folder // Import all components in library folder // require. Context (dir,deep,matching) // + const importFn = require.context('./', false, /\.vue$/) const defineDirective = app => {app.directive('lazyload', {mounted(el, binding) { const observer = new IntersectionObserver( ([{ isIntersecting }]) => { if (isIntersecting) { observer.unobserve(el) el.onerror = () => { el.src = defaultImg } el.src = binding.value } }, { threshold: 0.01}) observer.observe(el)}})} export default {install(app) { App provides component / / if you want to mount the directive function prototype app. Config. / / app.com ponent globalProperties way (XtxSkeleton. The name, XtxSkeleton) // app.component(XtxCarousel.name, XtxCarousel) // app.component(XtxMore.name, XtxMore) // app.component(XtxBread.name, XtxBread) // app.component(XtxBreadItem.name, ForEach (key => {+ // import component + const component = importFn(key).default + // App.component.name (component) +}) defineDirective(app)}}Copy the code