Доступ к динамическому дочернему компоненту - PullRequest
0 голосов
/ 11 мая 2018

Как получить доступ к моему подкомпоненту? Например, мой родительский компонент имеет следующий «динамический» компонент (компонент все время изменяется во время выполнения).

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

Как получить доступ к myCmp для вызова функции ... this.myCmp.doSomething() не работает. Обратите внимание, что использование emit здесь не является решением, потому что emit будет вызывать doSomething() для всех «динамических» компонентов, а не только для текущего.

Ниже приведен пример моего использования:

<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>

1 Ответ

0 голосов
/ 11 мая 2018

используйте свойство ref, приведите пример:

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/vue@2.5.16/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>
...