0%
全局注册加载组件库
思路:
入口文件中 import 所有组件
用 components 数组接收组件
遍历 components
Vue.component(component.name, component)
my-ui/index.js
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
| import Select from './Select'; import Link from './Link';
const COMPONENTS = [ Select, Link ];
const MyUI = {};
MyUI.install = (Vue, options) { COMPONENTS.forEach(component => { Vue.component(component.name, component); }); }
export default MyUI;
|
main.js 使用
1 2 3
| import MyUI from './my-ui'; Vue.use(MyUI, { });
|
按需注册加载组件库
通过 Vue.use 第二个参数配置
- 判断
options.components
是否有值
-
-
-
解构的方式实现
-
- 每个组件一个对象,实现一个 install 方法,单独
Vue.component(...)
- 导出一个总对象,实现 install 方法,遍历全局加载所有组件
export { MySelect, MyInput }
export default MyUI
my-ui/index.js
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29
| import Select from './Select'; import Link from './Link';
const COMPONENTS = [ Select, Link ];
const MyUI = {};
MyUI.install = (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 使用
1 2 3 4 5 6 7 8
| import MyUI from './my-ui';
Vue.use(MyUI, { components: [ 'MyButton', 'MyInput' ] });
|
解构的方式按需加载
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38
| 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 = (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;
|
使用:
1 2 3
| import { MySelect, MyLink } from './my-ui';
Vue.use(MySelect);
|