从组件实例中获取 Vue 组件对象 (class)

Get Vue component object (class) from component instance

问题

鉴于我在组件上下文中,我如何获得 组件对象组件对象 我的意思是当你 import Component from 'Component.vue'.

时得到的对象

当前进度

这是我发现的一种可能性。

const component = {
  methods: {
    getComponent: () => this,
    displayItem () {
      console.log('this.getComponent()', this.getComponent()) // undefined
      console.log('this', this) // component instance
      console.log('component', component) // what I need (component object)
    },
  },
}

export default component

缺点是它会杀死 IDE 支持。

我也手动检查了this

理想解

我希望看到的近似语法:this.$component

有什么意义?

  1. 通过:is="component"实例化组件。
  2. 执行 检查实例。

越接近vm.$options:

Vue.component('some-comp', {
  template: '<p>{{ message }}</p>',
  props: {name: String},
  data() {
    return {
      message: 'Open the console!'
    }
  },
  computed: {
    example() {
      return this.message.toUpperCase();
    }
  },
  watch: {
    message() {
      console.log('watcher triggered');
    }
  },
  mounted() {
    console.log(this.$options);
    console.dir(this.$options.__proto__);
  }
});
new Vue({
  el: '#app'
})
<script src="https://unpkg.com/vue"></script>

<div id="app">
  <some-comp :name="'Alice'"></some-comp>
</div>

不过你要的好像是constructor:

Vue.component('aaa-aaa', {
  template: '<div>AAA component</div>'
})
Vue.component('bbb-bbb', {
  template: '<div>BBB component</div>'
})

new Vue({
  el: '#app',
  mounted() {
    console.log(this.$refs.a1);
    console.log(this.$refs.a1.constructor);
    console.log(this.$refs.b1);
    console.log(this.$refs.b1.constructor);

    console.log('a1 a2', this.$refs.a1.constructor === this.$refs.a2.constructor)
    console.log('a1 b1', this.$refs.a1.constructor === this.$refs.b1.constructor)
    console.log('b1 b2', this.$refs.b1.constructor === this.$refs.b2.constructor)
    console.log('b2 a2', this.$refs.b2.constructor === this.$refs.a2.constructor)
  }
})
<script src="https://unpkg.com/vue"></script>

<div id="app">
  <aaa-aaa ref="a1"></aaa-aaa>
  <aaa-aaa ref="a2"></aaa-aaa>

  <bbb-bbb ref="b1"></bbb-bbb>
  <bbb-bbb ref="b2"></bbb-bbb>
</div>