componentOptions配置选项的作用和用法

3,871 阅读1分钟

componentOptions 可以通过vnode.componentOptions来访问,用来挂载部分组件选项来使用的。包括

{ Ctor, tag, propsData, listeners,children } 。非组件的componentOptions为空。

// 源码中体现代码如下:
// return a placeholder vnode
  const name = Ctor.options.name || tag
  const vnode = new VNode(
    `vue-component-${Ctor.cid}${name ? `-${name}` : ''}`,
    data, undefined, undefined, undefined, context,
    { Ctor, propsData, listeners, tag, children },
    asyncFactory
  )

用法

  1. 可以用来判断当前的vnode是不是组件。

    const isComponent = vnode.componentOptions
    
  2. 可以用来获取组件的名称

    const vonde = vnode.componentOptions.tag
    

    前提条件是在渲染组件的时候是采用字符串的形式,例如

    const comA = Vue.extend({})
    const comB = new Vue({
      components: {
        comA
      },
      render (h) {
        // return h('div', [h('comA')]) // 此时获取的vnode.componentOptions.tag为comA
        // return h('div', [h(comA)])  // 此时获取的vnode.componentOptions.tag为undefined
    })
    
  3. 最合适的获取组件名称的方式应该为:

    // 注意此时的componentOptions.tag为模版或者render书写的标签字符串,根据用户的书写可能不统一
    // 最好的方式还是使用componentOptions.Ctor.options.name
    const componentOptions = vnode.componentOptions;
    const componentName = componentOptions && componentOptions.Ctor.options.name || componentOptions.tag