同学们好,最近在开发的时候,碰到一个问题,需要父组件调用子组件的方法。本来是信手拈来的一件小事情,纠结了我好久,老是报错,提示not a function。网上查了一下,并没有能解决我问题的,甚至还有不少误导我的文章。有的文章中写道,子组件必须挂在父组件第一个子标签的中。于是我把我对父组件调用子组件方法的理解整理出来分享给大家。
需要注意的是,父组件中的子组件需要设置好ref、components
一、提示undefined
这种情况下,一般都是父组件调用子组件方法的时候,子组件还未渲染成功。要搞清楚这个问题,我们要搞清楚父子组件的生命周期就行了。
加载渲染过程
父beforeCreate->父created->父beforeMount->子beforeCreate->子created->子beforeMount->子mounted->父mounted
子组件更新过程
父beforeUpdate->子beforeUpdate->子updated->父updated
父组件更新过程
父beforeUpdate->父updated
销毁过程
父beforeDestroy->子beforeDestroy->子destroyed->父destroyed
这种情况下,我们可以在使用父组件调用子组件方法的时候,使用this.$nextTick()
clickBtn() {this.$nextTick(() => {console.log('我是父组件')this.$refs.myChild.init()})}
二、提示not a function
这种情况下,一般都是未找到子组件的ref。如下图所示,我的子组件放在v-for中,这时我的ref是个数组,就不能直接用this.$refs.myChild.init()。需要拿到ref的下标才行
clickBtn() {this.$nextTick(() => {console.log('我是父组件')this.list.forEach((item, index) => {this.$refs.myChild[index].init()})})}
最后,我把父子组件的代码贴出来,方便同学们去操作验证一下。
父组件
<template><div class="index"><div v-for="(item, index) in list" :key="index"><div>{{ item.value }}<child ref="myChild"></child></div></div><el-button @click="clickBtn">调用子组件方法</el-button></div></template><script>import child from '@/components/child.vue'export default {components: {child},data() {return {list: [{value: 1},{value: 2},{value: 3}]}},created() {this.clickBtn()},methods: {clickBtn() {this.$nextTick(() => {console.log('我是父组件')this.list.forEach((item, index) => {this.$refs.myChild[index].init()})})}}}</script><style lang="scss" scoped></style>
子组件
<template><div>子组件</div></template><script>export default {data() {return {}},// created(){// this.init()// },methods:{init(){console.log("我是子组件")},}}</script><style></style>
如果觉得《vue父组件调用子组件this.$refs报错 undefined not a function问题解决方法》对你有帮助,请点赞、收藏,并留下你的观点哦!