Vue添加全局复用组件

310 阅读1分钟

Vue添加全局复用组件

通常我使用组件都是哪里使用 improt 引用到哪里,但是如果我们要在多个组件中重复引用一个组件,每次都 improt 那就太麻烦了。例如:我们发现element UI, Ant Design Vue 的分页器不满足我们的需求时,我们就要自己封装一个分页器组件。我们要在多个组件中引用每次都去 improt 就很烦!

这时候就是我们就使用 Vue.useinstall() 对组件进行全局引用了

首先创建一个和 main.js 平级的文件夹 common 例如:

common.png

其次在 plugins 文件夹创建全局组件插件

// globalComponents.js中

const requireComponent = require.context('@/common', true, /\.(vue|jsx)$/)

const plugin = {
  install(Vue) {
    requireComponent.keys().forEach((fileName) => {
      const componentConfig = requireComponent(fileName).default
      Vue.component(componentConfig.name, componentConfig)
    })
  }
}

export default plugin
  • require.context是一个webpack的api,通过执行require.context函数获取一个特定的上下文,主要用来实现自动化导入模块.
  • 如果遇到从一个文件夹引入很多模块的情况,可以使用这个api,它会遍历文件夹中的指定文件,然后自动导入,使得不需要每次显式的调用import导入模块
  • require.context函数接受三个参数 读取文件路径,是否遍历文件子目录,匹配文件正则。
// index.js中

import globalComponents from './globalComponents'
const plugins = [globalComponents]
const plugin = {
  install(Vue){
    plugins.forEach((item)=>{
      Vue.use(item)
    })
  }
}

export default plugin

最后在 main.js

import plugin from './plugins'
Vue.use(plugin)

这时候我们就可以直接在组件中使用common中的组件而不用使用improt去引入