-
Vue实例作为事件总线,并在需要传递数据的组件中触发和监听事件。
EventBus.js import Vue from 'vue'; export const EventBus = new Vue();
-
在发送组件中触发事件:
SenderComponent.vue import { EventBus } from './EventBus'; export default { methods: { sendData() { EventBus.$emit('data-sent', data); } } };
在接收组件中监听事件:
ReceiverComponent.vue import { EventBus } from './EventBus'; export default { created() { EventBus.$on('data-sent', data => { // 处理接收到的数据 }); } };
-
路由参数:如果你的组件是通过Vue Router路由跳转的,你可以使用路由参数来传递数据。
在路由定义中设置参数:
const router = new VueRouter({ routes: [ { path: '/destination', component: DestinationComponent, props: true } ] });
在发送组件中导航到目标路由:
SenderComponent.vue export default { methods: { navigateToDestination() { this.$router.push({ path: '/destination', params: { data: yourData } }); } } };
在目标组件中接收参数:
DestinationComponent.vue export default { props: ['data'], created() { // 使用this.data访问传递的数据 } };
-
Vuex:作为全局状态管理方案,Vuex也可以在非父子组件之间传递数据。可以在Vuex store中存储数据,并在需要的组件中获取和修改这些数据。
vue兄弟组件(页面)之间通信的方法总结
于 2024-04-09 21:39:03 首次发布
![](https://img-home.csdnimg.cn/images/20240611030827.png)