组件通信
组件通信概念
组件通信,就是指组件与组件之间的数据传递
-
组件的数据是独立的,无法直接访问其他组件的数据。
-
想使用其他组件的数据,就需要组件通信
-
组件关系分类:
- 父子关系:
props
和$emit
- 非父子关系:
provide & inject
eventbus
- 父子关系:
父子通信流程
- 父组件通过
props
将数据传递给子组件 - 子组件利用
$emit
通知父组件修改更新
- 父向子传值步骤
- 给子组件以添加属性的方式传值
- 子组件内部通过props接收
- 模板中直接使用 props接收的值
- 子向父传值步骤
- $emit触发事件,给父组件发送消息通知
- 父组件监听$emit触发的事件
- 提供处理函数,在函数的形参中获取传过来的参数
<template>
<div>
<!-- 父组件通过props传递数据给子组件 -->
<child-component :message="message" @update-message="updateMessage"></child-component>
<p>父组件接收到的子组件传递的消息:{{ receivedMessage }}</p>
</div>
</template>
<script>
import ChildComponent from './ChildComponent.vue';
export default {
components: {
ChildComponent
},
data() {
return {
message: 'Hello from parent component',
receivedMessage: ''
};
},
methods: {
updateMessage(messageFromChild) {
// 父组件接收到子组件传递的消息
this.receivedMessage = messageFromChild;
}
}
}
</script>
<template>
<div>
<p>子组件接收到的父组件传递的消息:{{ message }}</p>
<!-- 子组件通过$emit触发事件,向父组件传递消息 -->
<button @click="sendMessageToParent">向父组件传递消息</button>
</div>
</template>
<script>
export default {
props: {
message: {
type: String,
required: true
}
},
methods: {
sendMessageToParent() {
const messageToParent = 'Hello from child component';
// 子组件通过$emit触发事件,将消息传递给父组件
this.$emit('update-message', messageToParent);
}
}
}
</script>