【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,不需要單獨引入

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