【vue开发技巧】vue 使用webpack require.context 全局引入组件,使用的时候就不需要单独再引入组件

 

index.js代码:


function changeStr (str) {
  return str.charAt(0).toUpperCase() + str.slice(1)
}
const requireComponent = require.context('./', false, /\.vue$/);
const install = (Vue) => {
  requireComponent.keys().forEach(fileName => {
    console.log(fileName)

    let config = requireComponent(fileName)
    console.log(config)
    let component = changeStr(fileName.replace(/^\.\//, '')).replace(/\.\w+$/, '')
    console.log(component)
    Vue.component(component, config.default || config)

  });
}

export default install

然后在main.js 中 引入 index.js

主要代码:

import index from './components/component/index.js'

Vue.use(index)

然后直接在需要的地方使用组件child1 和child2,不需要单独引入

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章