vue学习笔记10:vue全局组件注册和全局js引入

蛰伏已久 蛰伏已久 2018-09-11

有一些常用的组件或者js库,可能大部分页面都要使用,频繁的import未免显得啰嗦,这时可以考虑通过全局引入的方式实现

先看比较简单的js库全局引入

js库全局引入

js库的引入很简单,通过Vue.prototype即可

main.js 全局js引入核心代码

import Vue from 'vue'

import api from './utils/config/api' //要引入的js文件

Vue.prototype.$api=api

....//其他代码

.vue组件中使用:通过this.$api即可

this.$api.member_index

全局组件注册

通过我的测试,发现可以分为这两种,引用单个组件、引用某个文件夹下全部组件

单个组件全局注册

import TableBox from './components/mod/TableBox


 Vue.component('TableBox',TableBox)   //第一个为全局注册的组件名称,第二个为全局注册的组件模版

多个组件全局注册

import Vue from 'vue'    
import upperFirst from 'lodash/upperFirst'    
import camelCase from 'lodash/camelCase'    


const requireComponent = require.context(    
  
'./components/mod/',    // 组件所在目录  
false,                  // 是否不引用子目录组件
  /_base-[\w-]+\.vue$/    //通过正则表达式指明引入的文件名类型,比如以 _base- 开头的vue组件
)    

// For each matching file name...    
requireComponent.keys().forEach(fileName => {    
// Get the component config    
const componentConfig = requireComponent(fileName)    
// Get the PascalCase version of the component name    
const componentName = upperFirst(    
camelCase(    
fileName    
// Remove the "./_" from the beginning    
.replace(/^\.\/_/, '')    
// Remove the file extension from the end    
.replace(/\.\w+$/, '')    
)    
)    
// Globally register the component    
Vue.component(componentName, componentConfig.default || componentConfig)    
})

记住全局注册的行为必须在根 Vue 实例 (通过 new Vue) 创建之前发生

注意:太多的全局组件注册,会导致进入首页的文件量变大,所以尽量考虑将哪些最常用的且文件较小的组件进行全局引入,其他组件还是在需要的页面再引入


分享到

点赞(0)