require.context自动导入文件

2020-06-22  本文已影响0人  w_小伍

在components/common下新建myComponentsInstall.js


image.png
export default {
  install(Vue) {
    const components = require.context('@/components/common', false, /\.vue$/)
    // components.keys() 获取文件名数组
    components.keys().map(path => {
      // 获取组件文件名
      const fileName = path.replace(/(.*\/)*([^.]+).*/ig, "$2")
      // components(path).default 获取 ES6 规范暴露的内容,components(path) 获取 Common.js 规范暴露的内容
      Vue.component(fileName, components(path).default || components(path))
    })
  }
}

在main.js引入

import myComponentsInstall from './components/common/myComponentsInstall'
Vue.use(myComponentsInstall)

页面使用

<product></product>
上一篇 下一篇

猜你喜欢

热点阅读