Kevin Pimentel
Kevin Pimentel

Reputation: 1916

How to get an instance of a Vue Component from inside a component

From within my SectionComponent.vue file how can I grab an instance of a component I have imported?

import ButtonComponent from './ButtonComponent.vue'; 

To get an instance of it I want to do something like this:

buttonComponent = Vue.component(ButtonComponent);

I have my component listed/defined in my components array as ButtonComponent SO in theory I should be able to say:

let buttonComponent = Vue.component('button-component'); 

but that gives me undefined. What gives?

It does work if I register it globally and then grab an instance.

Is mounted not the right place to test this code? Is my mounted method fired before the imports? I am just looking for a bit of clarity here, if someone could explain I would appreciate it!

Upvotes: 2

Views: 243

Answers (2)

Bert
Bert

Reputation: 82489

Vue is a declarative framework, meaning you don't really do things imperatively. Instead, you formulate your template as a representation of state, and then Vue takes care of the DOM manipulation for you.

Here is an example based on what you've described you want to do.

console.clear()
Vue.component("button-component", {
  // identifier is just a property telling us which button this is so we 
  // can distinguish between them
  props:["identifier"],
  template: `<button @click="onClick">I'm button {{identifier}}</button>`,
  methods: {
    onClick() {alert(this.identifier)}
  }
})

new Vue({
  el: "#app",
  data:{
    howManyButtons: 0
  },
  methods: {
    onAddButton(){
      this.howManyButtons++
    }
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.16/vue.min.js"></script>

<div id="app">
  <button @click="onAddButton">Add a button component</button>
  <hr>
  <button-component v-for="btn in howManyButtons"
                    :identifier="btn"
                    :key="btn">
  </button-component>
</div>

In the above example we want to render a number of buttons based on how many times the "add a button" button has been clicked. To do that, we just increment a counter when the button is clicked. Then in the template we use the range variant of a v-for to render that many buttons.

<button-component v-for="btn in howManyButtons"
                  :identifier="btn"
                  :key="btn">
</button-component>

Hopefully this makes it clear that there is no point were we are telling Vue to add a button to the DOM. We just describe in the template that we want as many buttons as there are in our counter.

Upvotes: 1

Ru Chern Chong
Ru Chern Chong

Reputation: 3756

import ButtonComponent from './ButtonComponent.vue' 

Inside of the SectionComponent.vue component,

export default {
  components: { ButtonComponent },
  // Whatever else you have in here
  data() { return {} },
  computed: {}
}

Upvotes: 0

Related Questions