踩坑:vue 父组件$ref动态赋值并调用子组件方法

vue通过ref调用子组件发方法大家应该都知道,但是程序员的趣味就是相同的东西总是会踩在不同的坑里。

话不多说,直接有图有真相

父组件:

  <template>
  <div>
    <child :ref="`${yearInfo}`" :month="yearInfo" ></child>
    <child v-for="col in monthList" :ref="`${col}`" :month="col" :key="col"></child>
    <button @click="callSubmethod()">调用子组件方法</button>
  </div>
</template>
<script>
import child from '../components/refTestChild.vue'

export default {
  name: 'app',
  data () {
    return {
      monthList: [
        'january',
        'february',
        'march',
        'april',
        'may',
        'june',
        'july',
        'august',
        'september',
        'october',
        'november',
        'december'],
      yearInfo: 'year'
    }
  },
  components: {
    child
  },
  methods: {
    callSubmethod () {
      const refName = `${this.yearInfo}`
      this.$refs[refName].showMonth()

      this.monthList.forEach((filed) => {
        const refName = `${filed}`
        this.$refs[refName].showMonth()
      })
    }
  }
}
</script>

子组件:

<template>
  <div></div>
</template>

<script>
export default {
  prop: ['month'],
  computed: {},
  methods: {
    showMonth () {
      console.log(`当前组件${this.month}`)
    }
  },
  created () {}
}
</script>

点击按钮,最可怕的红色,year调用到了。然后就报错了!!这是针对我们month啊~
在这里插入图片描述
然后打印$refs发现,monthList遍历的组件VueComponent被包在了数组里面,所以调用不到那个方法。

在这里插入图片描述

然后改了下父组件的调用方法,month调用时候改成

this.$refs[refName][0]

父组件:

  methods: {
    callSubmethod () {
      console.log(this.$refs)
      const refName = `${this.yearInfo}`
      this.$refs[refName].showMonth()
      this.monthList.forEach((filed) => {
        const refName = `${filed}`
        this.$refs[refName][0].showMonth()
      })
    }
  }

然后看下是否成功了呢
在这里插入图片描述

哇塞塞,成功了~?

用antDesign vue的带行编辑功能的表格时候踩的坑,终于定位到了问题,赶紧记录下来,希望可以帮助更多的小伙伴~如果有更好的解决方法请分享给我,?

  • 4
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 3
    评论
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

高高i

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值