在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
}
}
})
有用请点赞,嘻嘻:)
本文深入探讨了Vue框架中组件、过滤器和指令的全局注册机制。通过分析核心代码,揭示了ASSET_TYPES如何影响Vue.component、Vue.filter和Vue.directive的实现。特别关注了component注册的复杂性及其与Vue.extend的关系。
646

被折叠的 条评论
为什么被折叠?



