组件注册 - 学习vue源码系列3.4
决定跟着黄轶老师的 vue2 源码课程好好学习下vue2
的源码,学习过程中,尽量输出自己的所得,提高学习效率,水平有限,不对的话请指正~
将vue 的源码clone 到本地,切换到分支2.6
。
Introduction
vue 中除了内置组件keep-alive
等,其他组件必须先注册才能使用,不然就会报错Unknown custom element...
vue 有两种注册方式:
- 全局注册
- 局部注册
先看个 demo
组件的两种注册和使用方式如下:
<div id="app"></div> <script src="/Users/zhm/mygit/vue/dist/vue.js"></script> <script> // 子组件 let Hello = { name: "Hello", template: "<div>hello</div>", }; // 全局组件 let appComponent = { name: "app", // 注册局部组件 components: { Hello }, // 使用局部组件 template: ` <div> {{msg}} <hello></hello> </div> `, data: () => ({ msg: "App" }), created() { console.log(`组件的$options.components`, this.$options.components); }, }; // 注册全局组件 Vue.component(appComponent.name, appComponent); console.log("Vue类上的options.components", Vue.options.components); // 根组件实例 let vueInstance = new Vue({ el: "#app", template: `<app></app>`, }); </script>
看下打印的结果:
注册全局组件,使用Vue.component(name,componentOptions)
注册局部组件,使用{components:{hello:hello}}
注册全局组件:Vue.component
看看Vue.component
怎么定义的,都做了啥,直接找有点难找,直接贴源码:
initAssetRegisters
就是在 Vue 上注册 3 个属性,components/filters/directives
。
// src/core/global-api/assets.js export function initAssetRegisters(Vue: GlobalAPI) { /** * Create asset registration methods. * ASSET_TYPES = [ 'component', 'directive', 'filter' ] */ ASSET_TYPES.forEach((type) => { Vue[type] = function ( id: string, definition: Function | Object ): Function | Object | void { if (!definition) { return this.options[type + "s"][id]; } else { /* istanbul ignore if */ if (process.env.NODE_ENV !== "production" && type === "component") { validateComponentName(id); } if (type === "component" && isPlainObject(definition)) { definition.name = definition.name || id; definition = this.options._base.extend(definition); } if (type === "directive" && typeof definition === "function") { definition = { bind: definition, update: definition }; } this.options[type + "s"][id] = definition; return definition; } }; }); }
看源码脑壳疼的地方就是,即便是简单的功能,但为了全面考虑,看起来就感觉多了一层窗户纸,模模糊糊的,上面的内容简化下:
// component简写为cp Vue.components = function (cpName, cpOptions) { // 确保component上面有name属性 cpOptions.name = cpOptions.name | cpName; // Vue.extend其实将cpOptions变成一个Vue的子类. const cpClass = Vue.extend(cpOptions); // 所以全局组件一定在Vue.options.components里 Vue.options.components[cpName] = cpClass; return cpClass; }; // Vue.extend其实将cpOptions变成一个Vue的子类,简化下代码如下 Vue.extend = function (cpOptions) { const Sub = function VueComponent(options) { this._init(options); }; Sub.prototype = Object.create(Vue.prototype); // 不同的字段合并策略不一样 Sub.options = mergeOptions(Vue.options, cpOptions); return Sub; };
Vue.options.components[cpName] = cpClass
可以看到,全局组件都在Vue.options.components
,组件名和组件类一一对应,这样使用组件的时候,就直接调出相应的组件类了。
使用全局组件
组件类的options
上已经合并了Vue.options
,而在组件实例化的阶段,会再次执行mergeOptions
的操作,将VueComponent.options.components
合并到vm.$options.components
。
然后在创建 vnode
的过程中,会执行 _createElement
方法,我们再来回顾一下这部分的逻辑,它的定义在 src/core/vdom/create-element.js
中:
export function _createElement ( context: Component, tag?: string | Class<Component> | Function | Object, data?: VNodeData, children?: any, normalizationType?: number ): VNode | Array<VNode> { // ... let vnode, ns if (typeof tag === 'string') { let Ctor if (isDef(Ctor = resolveAsset(context.$options, 'components', tag))) { // component vnode = createComponent(Ctor, data, context, children, tag) } }
这里看到,根据 tag,然后在options.components
里找到相应的Ctor
,然后再创建组件的vnode
resolveAsset
就是根据 tag
找到Ctor
的方法。
// src/core/utils/options.js export function resolveAsset( options: Object, type: string, id: string, warnMissing?: boolean ): any { // type就是 是components 还是 filters之类的 const assets = options[type]; // id其实这边指的是组件名,或者说是组件的tag也行 if (hasOwn(assets, id)) return assets[id]; const camelizedId = camelize(id); // 驼峰的形式 if (hasOwn(assets, camelizedId)) return assets[camelizedId]; // 首字母大写的形式 const PascalCaseId = capitalize(camelizedId); // 连字符的形式 if (hasOwn(assets, PascalCaseId)) return assets[PascalCaseId]; // fallback to prototype chain const res = assets[id] || assets[camelizedId] || assets[PascalCaseId]; if (process.env.NODE_ENV !== "production" && warnMissing && !res) { warn("Failed to resolve " + type.slice(0, -1) + ": " + id, options); } return res; }
这里先用id
找,不行就驼峰式id
找,首字母大写找,连字符找,所以id
形式三种形式都行,找到就返回Ctor
注册局部组件
注册局部组件,其实就是在当前组件的options里加上components:{hello}
,而mergeOptions
的时候肯定被合并到vm.$options.components
上,组件实例化的时候,依旧通过resolveAsset
拿到对应的Ctor
当然局部组件,只能在组件内才能使用组件。 全局组件之所以能被所有的组件使用,是因为组件实例化的时候,Vue.options.components
会被合并到vm.$options.components
。