<template>
<div class="father">
<component :is="currentTab" ref="child"></component>
<button @click="clickFn">点击调用子组件方法</button>
</div>
</template>
//引入的2个子组件
import childone from ‘‘
import childtwo from ‘‘
data(){
return{
//动态子组件
currentTab:‘childone‘
}
}
methods:{
//点击调用子组件方法,注意要加上this.$nextTick,否则会出现ref报错
clickFn(){
this.currentTab = ‘‘childtow‘ //切换组件后触发子组件方法
this.$nextTick(()=>{
this.$refs.child.childFn()
})
}
}
子组件:每一个子组件都包含这个方法
methods{
childFn(){// 子组件方法
}
}
原理就是动态组件切换时,调用子组件的方法必须在组件全部加载完成后再去调用,否则会出现调用了上一个动态组件的方法。