sazr
sazr

Reputation: 25928

Access dynamic child component

How do I access my subcomponent? For example my parent component has the following 'dynamic' component (the component changes all the time at runtime).

<template>
  <!-- The below component count be Component1 or Component2, etc. -->
  <component id="my-cmp" v-if="templateComponent" :is="templateComponent"></component>
</template>

How can I access myCmp to call a function...this.myCmp.doSomething() doesn't work. Please note using emit here isn't a solution because emit will call doSomething() on all 'dynamic' components not just the current one.

Below is an example of my usage:

<template>
  <!-- The below component count be Component1 or Component2, etc. -->
  <component id="my-cmp" v-if="templateComponent" :is="templateComponent"></component>
</template>

<script type="text/javascript">
export default {

  components: {
    'cmp1': Component1,
    'cmp2': Component1,
  },

  computed: {
    templateComponent() {
      // ...some logic that will determine if to use/chage to Component1 or Component2
      return 'cmp1'
    },
  },

  methods: {
    someTrigger() {
      // how can I reference #my-cmp?
      // For the purpose of; myCmp.doSomething()

      // I have tried the below technique BUT this will call doSomething 
      // on BOTH components not just the current/visible one

      this.$emit('doSomethingNow') // Component1 and Component2 register using this.$parent.$on('doSomethingNow', this.doSomething)
    }
  }
}
</script>

Upvotes: 3

Views: 1868

Answers (1)

jacky
jacky

Reputation: 1446

use ref property,give you an example:

Vue.component('com1',{
  template: '<div>component com1</div>',
  methods: {
    fn () {
      alert('method called')
    }
  }
})

var app = new Vue({
  el: '#app',
  data () {
  },
  computed: {
    whichCom () {
      return 'com1'
    }
  },
  methods: {
    btnClick () {
      this.$refs.myCom.fn()
    }
  }
})
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/vue.js"></script>
<div id="app">
  <component ref="myCom" v-if="whichCom" :is="whichCom"></component>
  <button @click="btnClick">call method of com1</button>
</div>

Upvotes: 2

Related Questions