首页 > 解决方案 > 访问动态子组件

问题描述

如何访问我的子组件?例如,我的父组件具有以下“动态”组件(该组件在运行时一直在更改)。

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

标签: vue.jsvuejs2vue-component

解决方案


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


推荐阅读