vue3 组件通信 子传父 父传子
时间: 2025-05-13 20:36:34 浏览: 21
### Vue3 父子组件通信方法
#### 子组件向父组件传递数据
在 Vue3 中,子组件可以通过 `emit` 方法向父组件发送事件并附带数据。具体实现如下:
1. **子组件定义要传递的数据**
在子组件的 `data()` 函数中定义需要传递给父组件的数据变量 `transmsg`[^1]。
```javascript
export default {
data() {
return {
transmsg: '我是子组件传递的值'
};
},
methods: {
sendMessageToParent() {
this.$emit('custom-event', this.transmsg); // 发送自定义事件 custom-event 并携带数据
}
}
};
```
2. **父组件监听子组件发出的事件**
父组件通过绑定子组件上的自定义事件来接收来自子组件的消息。
```html
<template>
<ChildComponent @custom-event="handleCustomEvent" />
</template>
<script>
import ChildComponent from './ChildComponent.vue';
export default {
components: { ChildComponent },
methods: {
handleCustomEvent(message) {
console.log('接收到子组件消息:', message);
}
}
};
</script>
```
---
#### 父组件向子组件传递数据
父组件可以利用 Props 将数据传递到子组件中。Props 是一种单向下行的数据流机制。
1. **父组件传递数据至子组件**
父组件通过属性的方式将数据传入子组件。
```html
<template>
<ChildComponent :parentMessage="messageFromParent" />
</template>
<script>
import ChildComponent from './ChildComponent.vue';
export default {
components: { ChildComponent },
data() {
return {
messageFromParent: '这是来自父组件的消息'
};
}
};
</script>
```
2. **子组件接收 Prop 数据**
子组件声明接受的 Prop 属性,并将其用于模板或其他逻辑中。
```javascript
export default {
props: ['parentMessage'], // 声明 prop
mounted() {
console.log('接收到父组件消息:', this.parentMessage);
}
};
```
---
#### 父组件访问子组件中的 Data 数据
如果父组件需要直接获取子组件内部的状态(不推荐频繁使用),可以借助 `$refs` 实现[^2]。
1. **子组件暴露特定的方法或状态**
使用 `defineExpose` 显式暴露子组件的内容(Vue3 Composition API 特性)。
```javascript
<script setup>
import { ref } from 'vue';
const childData = ref('我是子组件的数据');
defineExpose({ childData });
</script>
```
2. **父组件通过 $refs 访问子组件数据**
父组件可以在挂载完成后通过 `$refs` 获取子组件实例及其公开内容。
```html
<template>
<ChildComponent ref="childRef" />
<button @click="accessChildData">访问子组件数据</button>
</template>
<script>
import ChildComponent from './ChildComponent.vue';
export default {
components: { ChildComponent },
methods: {
accessChildData() {
console.log(this.$refs.childRef.childData); // 输出子组件暴露的数据
}
}
};
</script>
```
---
### 总结
- 子组件向父组件传递数据主要依赖于 `$emit` 和自定义事件。
- 父组件向子组件传递数据则通过 Props 完成。
- 如果确实需要跨边界访问子组件内部状态,则可采用 `$refs` 或显式暴露接口的方式完成交互。
阅读全文
相关推荐















