vue 父组件调用子组件函数
时间: 2023-10-31 12:18:16 浏览: 104
在Vue中,父组件可以通过ref
来访问子组件的实例,并调用子组件的方法。以下是一个示例:
<template>
<div>
<button @click="callChildFunction">调用子组件函数</button>
<ChildComponent ref="childRef"></ChildComponent>
</div>
</template>
<script>
import ChildComponent from './ChildComponent.vue';
export default {
components: {
ChildComponent
},
methods: {
callChildFunction() {
// 通过 $refs 访问子组件实例
this.$refs.childRef.childFunction();
}
}
}
</script>
在上面的示例中,父组件中使用ref
来引用子组件,并将其命名为"childRef"。然后在callChildFunction
方法中,通过this.$refs.childRef
来获取子组件的实例,并调用子组件的函数childFunction()
。
注意:如果子组件是异步加载的,需要在确保子组件已经加载完成后才能调用子组件的函数,可以使用$nextTick
方法来实现,例如:
callChildFunction() {
this.$nextTick(() => {
this.$refs.childRef.childFunction();
});
}
这样可以确保在调用子组件函数时子组件已经完全渲染和初始化。
相关推荐


















