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