导航


HTML

CSS

JavaScript

浏览器 & 网络

版本管理

框架

构建工具

TypeScript

性能优化

软实力

算法

UI、组件库

Node

业务技能

针对性攻坚

AI


全局注册加载组件库

思路:

  1. 入口文件中 import 所有组件
  2. 用 components 数组接收组件
  3. 遍历 components
    1. Vue.component(component.name, component)

my-ui/index.js

import Select from './Select';
import Link from './Link';

const COMPONENTS = [
	Select,
  Link
];

const MyUI = {};

MyUI.install = function(Vue, options) {
	COMPONENTS.forEach(component => {
  	Vue.component(component.name, component);
  });
}

export default MyUI;

main.js 使用

import MyUI from './my-ui';
Vue.use(MyUI, {
}); // 这里的第二个参数: {} 作为整体,就是 options 接收

按需注册加载组件库

my-ui/index.js

import Select from './Select';
import Link from './Link';

const COMPONENTS = [
	Select,
  Link
];

const MyUI = {};

MyUI.install = function(Vue, options) {
	if (options && options.components) {
  	const components = options.components;

    components.forEach(componentName => {
    	COMPONENTS.forEach(component => {
      	if (componentName === component.name) {
        	Vue.component(component.name, component);
        }
      });
    });
  } else {
  	COMPONENTS.forEach(component => {
    	Vue.component(component.name, component);
    });
  }
}

export default MyUI;

main.js 使用

import MyUI from './my-ui';

Vue.use(MyUI, {
	components: [
  	'MyButton',
    'MyInput'
  ]
});

解构的方式按需加载

import Select from './Select';
import Link from './Link';

const COMPONENTS = [
	Select,
  Link
];

const MyUI = {};
const MySelect = {};
const MyLink = {};
MySelect.install = Vue => Vue.component(Select.name, Select);
MyLink.install = Vue => Vue.component(Link.name, Link);

export {
	MySelect,
  MyLink
}

MyUI.install = function(Vue, options) {
	if (options && options.components) {
  	const components = options.components;

    components.forEach(componentName => {
    	COMPONENTS.forEach(component => {
      	if (componentName === component.name) {
        	Vue.component(component.name, component);
        }
      });
    });
  } else {
  	COMPONENTS.forEach(component => {
    	Vue.component(component.name, component);
    });
  }
}

export default MyUI;

使用:

import { MySelect, MyLink } from './my-ui';

Vue.use(MySelect);