父组件怎么触发子组件的方法
时间: 2023-09-13 14:11:17 浏览: 42
要在父组件中触发子组件的方法,可以使用`ref`引用子组件,并通过该引用调用子组件的方法。以下是一个示例:
父组件:
```vue
<template>
<div>
<p>父组件</p>
<ChildComponent ref="childRef" />
<button @click="triggerChildMethod">触发子组件方法</button>
</div>
</template>
<script>
import ChildComponent from './ChildComponent.vue';
export default {
components: {
ChildComponent
},
methods: {
triggerChildMethod() {
this.$refs.childRef.childMethod(); // 通过ref调用子组件的方法
}
}
}
</script>
```
子组件:
```vue
<template>
<div>
<p>子组件</p>
</div>
</template>
<script>
export default {
methods: {
childMethod() {
console.log('子组件的方法被调用');
}
}
}
</script>
```
在父组件中使用`ref`来引用子组件,并给它一个名称(例如`childRef`)。然后,在父组件的方法中,通过`this.$refs.childRef`来访问子组件实例,并调用其方法(例如`childMethod()`)。
当点击父组件中的按钮时,会触发父组件的`triggerChildMethod`方法,该方法通过`this.$refs.childRef.childMethod()`调用子组件的`childMethod`方法。
这样就实现了父组件触发子组件方法的功能。请注意,在使用`ref`引用子组件时,确保子组件已经渲染完成。