blog icon indicating copy to clipboard operation
blog copied to clipboard

at-ui源码阅读

Open huruji opened this issue 6 years ago • 0 comments

组件的注册方式

作为一个UI库,肯定是需要全局使用的,因此必然需要使用插件的方式。即 Vue.use(My-UI) 。因此全局来说应该是注册为插件的形式。一个插件作为一个对象时需要提供install函数,我们可以在这个函数中对我们所有的 component 进行全局注册,这样就不必要在在每次使用组件的时候都 import 了,即:

module.export = {
  install: function (Vue, opts = {}) {
      for (const item in components) {  
            if (components[item].name) {
                Vue.component(components[item].name, components[item])
            }
       }
     // ....
    }
}

很可能一部分用户只是想要使用其中的一部分组件,当然用户可以每个单文件中使用 import 的方式,之后声明为 components ,但是我们需要考虑到一些组件很可能用户会重复使用到,这些 组件可以作为全局组件 应该是更好的设计,所以我们同样可以为 单个组件 添加一个 install 方法,以便于以 插件 的形式注册为全局组件,即设计为:

import MyUiComponent from './src/myUiComponent.vue'

MyUiComponent.install = function(Vue) {
    Vue.component(MyUiComponent.name, MyUiComponent)
}

export default MyUiComponent

huruji avatar Apr 14 '18 17:04 huruji