vue父组件调用子组件方法,子组件调用父组件方法
时间: 2025-07-10 07:09:58 浏览: 12
在 Vue 框架中,父子组件之间的方法调用是常见的开发需求。以下是基于 Vue 2 和 Vue 3 的实现方式,涵盖了父组件调用子组件方法以及子组件调用父组件方法的完整实现。
### 父组件调用子组件方法
#### Vue 2 实现方式
在 Vue 2 中,父组件通过 `this.$refs` 获取子组件实例,并直接调用其方法。具体实现如下:
```vue
<!-- 子组件 ChildComponent.vue -->
<template>
<div class="child">
<button @click="childMethod">子组件</button>
</div>
</template>
<script>
export default {
methods: {
childMethod() {
console.log('子组件方法被调用');
}
}
}
</script>
```
```vue
<!-- 父组件 ParentComponent.vue -->
<template>
<div class="parent">
<button @click="handleParentClick">调用子组件方法</button>
<ChildComponent ref="childRef" />
</div>
</template>
<script>
import ChildComponent from './ChildComponent.vue';
export default {
components: { ChildComponent },
methods: {
handleParentClick() {
this.$refs.childRef.childMethod(); // 调用子组件方法 [^3]
}
}
}
</script>
```
#### Vue 3 实现方式(使用 `<script setup>` 语法)
在 Vue 3 中,需要使用 `defineExpose` 显式暴露子组件的方法,以便父组件通过 `ref` 调用:
```vue
<!-- 子组件 ChildComponent.vue -->
<template>
<div class="container">
<div>
<span>父组件触发了 {{ count }} 次子组件的方法</span>
</div>
</div>
</template>
<script setup>
import { ref } from 'vue';
const count = ref(0);
const firstEvent = () => {
count.value++;
};
defineExpose({ firstEvent }); // 暴露方法给父组件调用 [^2]
</script>
```
```vue
<!-- 父组件 ParentComponent.vue -->
<template>
<div class="parent">
<button @click="handleParentClick">调用子组件方法</button>
<ChildComponent ref="childRef" />
</div>
</template>
<script setup>
import { ref } from 'vue';
import ChildComponent from './ChildComponent.vue';
const childRef = ref();
const handleParentClick = () => {
childRef.value.firstEvent(); // 调用子组件方法 [^2]
};
</script>
```
### 子组件调用父组件方法
子组件通常通过 `$emit` 触发事件,由父组件监听并执行相应的方法。
```vue
<!-- 子组件 ChildComponent.vue -->
<template>
<div class="child">
<button @click="childMethod">子组件按钮</button>
</div>
</template>
<script>
export default {
emits: ['child-event'],
methods: {
childMethod() {
this.$emit('child-event'); // 触发事件通知父组件 [^1]
}
}
}
</script>
```
```vue
<!-- 父组件 ParentComponent.vue -->
<template>
<div class="parent">
<ChildComponent @child-event="handleChildEvent" />
<p>父组件响应次数:{{ parentCount }}</p>
</div>
</template>
<script>
import ChildComponent from './ChildComponent.vue';
export default {
components: { ChildComponent },
data() {
return {
parentCount: 0
};
},
methods: {
handleChildEvent() {
this.parentCount++;
console.log('父组件方法被子组件触发');
}
}
}
</script>
```
### 总结
- **Vue 2** 中,父组件通过 `this.$refs` 调用子组件方法,子组件通过 `$emit` 通知父组件。
- **Vue 3** 中,父组件通过 `ref` 获取子组件实例,并结合 `defineExpose` 调用其方法;子组件同样通过 `$emit` 或 `defineEmits` 与父组件通信。
阅读全文
相关推荐













