3
votes

Question

Given I am in component context, how do I get the component object? By component object I mean the object you get when you import Component from 'Component.vue'.

Current progress

Here's one possibility I found.

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

The downside though is that it kills IDE support.

I also checked this manually.

Ideal solution

The approximation to syntax I'd like to see: this.$component.

What's the point?

  1. Instantiate components via :is="component".
  2. Perform instance of check.
1
Inside the component's methods you can do this. - Phiter
@Phiter Nope. That's component instance. - Yauheni Prakopchyk
maybe vm.$options._Ctor[0] but i'm not sure what [0] is here. - tsh

1 Answers

2
votes

The closer you got is 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>

But it seems what you want is 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>