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