【问题标题】:Access dynamic child component访问动态子组件
【发布时间】:2018-10-21 16:27:11
【问题描述】:

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

<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.js vuejs2 vue-component


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-06-15
      • 1970-01-01
      • 1970-01-01
      • 2015-04-25
      • 1970-01-01
      • 1970-01-01
      • 2018-07-17
      • 1970-01-01
      相关资源
      最近更新 更多