vue3 父组件调用子组件方法
时间: 2023-10-31 19:22:40 浏览: 110
在 Vue 3 中,父组件可以通过使用 ref
或 $refs
来访问子组件的实例,并且可以调用子组件的方法。
下面是一个示例代码,演示了父组件如何调用子组件的方法:
<template>
<div>
<child-component ref="childRef"></child-component>
<button @click="callChildMethod">调用子组件方法</button>
</div>
</template>
<script>
import ChildComponent from './ChildComponent.vue';
export default {
components: {
ChildComponent
},
methods: {
callChildMethod() {
// 通过 $refs 访问子组件实例
this.$refs.childRef.childMethod();
}
}
}
</script>
在上述代码中,我们首先在父组件中引入了子组件 ChildComponent
。然后,我们在父组件的 data
选项中使用 ref
属性来创建一个引用,命名为 childRef
,并在模板中使用了这个引用。
接下来,在父组件的 callChildMethod
方法中,我们通过 this.$refs.childRef
来访问子组件的实例,并调用子组件的方法 childMethod()
。
这样,当点击父组件中的按钮时,就会调用子组件的方法。
请注意,在使用 $refs
访问子组件之前,需要确保子组件已经被渲染到 DOM 中。
相关推荐
















