组件通信1

组件通信1 一、外层组件向内层组件通信Props 属性传递不可直接修改// 外层组件 A template div Child :messageAmsg :count10 / /div /template script import Child from ./Child.vue; export default { components: { Child }, data() { return { Amsg: 我是外层组件A的数据 }; } }; /script// 内层组件 template div p消息{{ message }}/p // 显示“我是外层组件A的数据” p计数{{ count }}/p // 若未从外层组件传值显示默认值“0” /div /template script export default { props: { message: String, // 类型校验 count: { type: Number, default: 0 } } }; /script要点数据是单向的外层组件更新内层组件自动更新但内层组件不能直接修改props会报错。如果内层组件需要基于props做修改应该用data或computed来转存。二、内层组件向外层组件通信$emit内层组件通过$emit触发一个自定义事件外层组件在内层组件标签上监听这个事件并处理。// 内层 template button clicksendData点我传值111/button /template script export default { data() { return { childMsg: 来自内层组件的问候 }; }, methods: { sendData() { this.$emit(child-event, this.childMsg); // 第一个参数是事件名后面是传递的数据 } } }; /script// 外层 template div Child child-eventhandleChildEvent / p收到子组件的消息{{ receivedMsg }}/p // 显示“来自内层组件的问候” /div /template script import Child from ./Child.vue; export default { components: { Child }, data() { return { receivedMsg: }; }, methods: { handleChildEvent(payload) { this.receivedMsg payload; } } }; /script要点$emit可以携带多个参数外层组件的方法里按顺序接收。三、同级组件通信两个没有调用关系处于同一级的组件要通信Vue 2 中有三种常见方式1. 事件总线EventBus创建一个空的 Vue 实例作为“中介”用它来$emit和$on事件。创建 bus.js// utils/bus.js import Vue from vue; export const bus new Vue();发送方组件组件Aimport { bus } from /utils/bus; export default { methods: { sendToComponent() { bus.$emit(share-data, { name: Alice }); } } };接收方组件组件Bimport { bus } from /utils/bus; export default { data() { return { sharedData: null }; }, created() { bus.$on(share-data, (data) { this.sharedData data; }); }, beforeDestroy() { bus.$off(share-data); // 必须手动销毁监听防止内存泄漏 } };缺点事件名容易冲突。不便于追踪数据流不像 Vuex 有 Devtools。忘记$off会导致内存泄漏。适用场景少量、简单、临时的同级组件通信不想引入 Vuex 时。2. Vuex3. 共同的外层组件中转状态提升如果同级组件BC被同一个外层组件A调用可以把共享状态提升到A组件然后通过 props 分发给BC组件BC组件通过$emit修改A组件状态。总结能用props$emit解决的就用它们保持组件独立。当数据需要在很多地方共享或跨多个层级时再考虑 Vuex。EventBus 只在极简单、一次性场景下使用正式项目里尽量用 Vuex 或状态提升替代。