04-Vue中的资源全局注册函数

本文深入探讨了Vue框架中组件、过滤器和指令的全局注册机制。通过分析核心代码,揭示了ASSET_TYPES如何影响Vue.component、Vue.filter和Vue.directive的实现。特别关注了component注册的复杂性及其与Vue.extend的关系。

在Vue源码中有三个类型被称为资源(asset),为什么这么叫我就不知道了。这三个是component、filter和directive。在shared/constants.js中有一个常量数组ASSET_TYPES,就是这三个东西。Vue提供了这三个的全局注册函数,挂载了Vue上,Vue.component、Vue.filter和Vue.directive,分别用来你全局注册组件、过滤器和指令。

现在要谈的是全局注册函数core/global-api/assets.js

下面代码就是在Vue上添加这三个全局注册函数的。全局注册函数集get和set于一身。指令directive和过滤器filter的注册都是简单的,在directive注册过程中还做了一下标准化,把所有directive都转换成了对象形式。最复杂的是component的注册。最终又导向了Vue.extend,参考这里

ASSET_TYPES.forEach(type => {
    Vue[type] = function (
      id: string,
      definition: Function | Object
    ): Function | Object | void {
      // 只有一个参数,get
      if (!definition) {
        return this.options[type + 's'][id]
      } else {
        /* istanbul ignore if */
        // 非生产环境下,验证一下组件名的有效性
        if (process.env.NODE_ENV !== 'production' && type === 'component') {
          validateComponentName(id)
        }
        // 组件的注册最复杂了
        // 需要把传进来的组件options即definition转换成组件类,这个组件类都是
        // 继承Vue的,具体过程在extend方法中。这个_base就是Vue自己
        if (type === 'component' && isPlainObject(definition)) {
          definition.name = definition.name || id
          definition = this.options._base.extend(definition)
        }
        // 指令标准化,保证最后存在directives中的都是对象格式
        if (type === 'directive' && typeof definition === 'function') {
          definition = { bind: definition, update: definition }
        }
        // set
        this.options[type + 's'][id] = definition
        return definition
      }
    }
  })

有用请点赞,嘻嘻:)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值