父組件
<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(){// 子組件方法
}
}
原理就是動態組件切換時,調用子組件的方法必須在組件全部加載完成后再去調用,否則會出現調用了上一個動態組件的方法。