问题描述
项目需求是在父组件中调用子组件中的方法,但是实际调用时却报错:TypeError: Cannot read properties of undefined (reading 'reload')
问题代码:
父组件:
handleEdit(id) {//编辑
this.update_drawer = true;
this.$refs.UpdateUser.reload(123);
},
子组件:
export default {
props:["usermsg"],
data(){
return{
ruleForm:[]
}
},
mounted(){
},
methods:{
reload(e){//需要调用的子组件方法
console.log(e)
}
}
}
原因分析:
写demo排查问题,发现在demo里,父组件调用子组件没有问题,而当前代码与demo中的代码完全一致,唯一不同的是项目内子组件是放置于element
抽屉中的,于是考虑出现bug的原因可能是element
抽屉打开前就调用了子组件方法。
解决方案:
添加 this.$nextTick,问题解决!
handleEdit(id) {//编辑
this.update_drawer = true;
this.$nextTick(() => {
this.$refs.UpdateUser.reload(123);
})
},