当前位置: 首页 > news >正文

vue2两个组件间如何传递消息

Vue 2 组件间传递消息有多种方式,根据组件关系和场景选择合适的方法:

1. 父子组件通信

Props / $emit(标准方式)

vue

复制

<!-- 父组件 Parent.vue --> <template> <div> <h2>父组件</h2> <Child :message="parentMsg" @child-event="handleChildEvent" /> </div> </template> <script> import Child from './Child.vue' export default { components: { Child }, data() { return { parentMsg: '来自父组件的消息' } }, methods: { handleChildEvent(data) { console.log('收到子组件消息:', data) } } } </script>

vue

复制

<!-- 子组件 Child.vue --> <template> <div> <p>收到: {{ message }}</p> <button @click="sendToParent">通知父组件</button> </div> </template> <script> export default { props: ['message'], methods: { sendToParent() { this.$emit('child-event', { msg: '子组件发来的数据', time: Date.now() }) } } } </script>

2. 兄弟组件通信

Event Bus(事件总线)

JavaScript

复制

// utils/eventBus.js import Vue from 'vue' export const eventBus = new Vue()

vue

复制

<!-- 组件 A --> <template> <button @click="sendMsg">发送给兄弟组件</button> </template> <script> import { eventBus } from '@/utils/eventBus' export default { methods: { sendMsg() { eventBus.$emit('brother-msg', { data: 'Hello Brother' }) } } } </script>

vue

复制

<!-- 组件 B --> <template> <div>收到: {{ msg }}</div> </template> <script> import { eventBus } from '@/utils/eventBus' export default { data() { return { msg: '' } }, created() { // 监听事件 eventBus.$on('brother-msg', this.handleMsg) }, beforeDestroy() { // 必须移除监听,防止内存泄漏 eventBus.$off('brother-msg', this.handleMsg) }, methods: { handleMsg(data) { this.msg = data.data } } } </script>

3. 跨层级组件通信

Provide / Inject(祖先 ↔ 后代)

vue

复制

<!-- 祖先组件 --> <template> <div> <GrandChild /> </div> </template> <script> export default { provide() { return { appConfig: this.config, getMessage: this.getMessage } }, data() { return { config: { theme: 'dark', lang: 'zh' } } }, methods: { getMessage(msg) { console.log('深层组件传来:', msg) } } } </script>

vue

复制

<!-- 深层孙组件 --> <template> <button @click="sendUp">向祖先传消息</button> </template> <script> export default { inject: ['appConfig', 'getMessage'], created() { console.log('配置:', this.appConfig) // { theme: 'dark', lang: 'zh' } }, methods: { sendUp() { this.getMessage('来自深层组件的问候') } } } </script>

4. 全局状态管理

Vuex(推荐用于复杂应用)

JavaScript

复制

// store/index.js import Vue from 'vue' import Vuex from 'vuex' Vue.use(Vuex) export default new Vuex.Store({ state: { message: '', count: 0 }, mutations: { SET_MESSAGE(state, msg) { state.message = msg }, INCREMENT(state) { state.count++ } }, actions: { updateMessage({ commit }, msg) { commit('SET_MESSAGE', msg) } }, getters: { getMessage: state => state.message } })

vue

复制

<!-- 组件中使用 --> <template> <div> <p>消息: {{ message }}</p> <p>计数: {{ count }}</p> <button @click="changeMsg">修改消息</button> </div> </template> <script> import { mapState, mapMutations, mapActions } from 'vuex' export default { computed: { ...mapState(['message', 'count']), // 或使用 getter msg() { return this.$store.getters.getMessage } }, methods: { ...mapMutations(['INCREMENT']), ...mapActions(['updateMessage']), changeMsg() { // 方式1: 直接 commit this.$store.commit('SET_MESSAGE', '新消息') // 方式2: dispatch action this.updateMessage('通过 action 修改') this.INCREMENT() } } } </script>

5. $refs 直接调用(慎用)

vue

复制

<template> <Child ref="childRef" /> </template> <script> export default { methods: { callChildMethod() { // 直接调用子组件方法 this.$refs.childRef.doSomething('父组件传来的数据') } } } </script>

选择指南

表格

场景推荐方案说明
父子组件Props / $emit最标准、单向数据流
兄弟组件Event Bus / Vuex简单用 Bus,复杂用 Vuex
跨多层组件Provide/Inject避免层层传递 props
全局共享状态Vuex可预测、可调试、DevTools 支持
临时/一次性通信Event Bus轻量,但注意解绑事件

⚠️ 注意事项:

  • Event Bus 在组件销毁前必须用$off移除监听

  • $refs避免滥用,破坏组件封装

  • Vue 3 中 Event Bus 被移除,建议用 mitt 替代或直接用 Pinia/Vuex

http://www.jsqmd.com/news/517213/

相关文章:

  • 告别复杂配置!SDXL 1.0电影级绘图工坊一键部署指南,纯本地运行,数据安全
  • RustFS:构建云原生时代的高性能、安全对象存储实践
  • 【ROS2】机械臂抓取——gazebo_grasp_plugin参数调优与实战避坑
  • Rust 升级受阻:深入解析 rustup update stable 网络连接失败
  • STEP3-VL-10B开箱即用:Supervisor自动启动,无需复杂配置
  • PP-DocLayoutV3与YOLOv8协同:实现文档中插图的细粒度分类
  • 技术解析 2DGS vs 3DGS | SIGGRAPH 2024 新方法如何用‘二维圆盘’实现精准表面重建
  • 选对城市对年轻人的发展到底有多重要?
  • Qwen2.5-VL-7B实战:Ollama部署教程,5步搞定视觉对话AI
  • Harmonyos应用实例166:垂径定理互动演示
  • K8S持久化存储新选择:阿里云OSS CSI驱动深度配置与性能调优
  • 海康二次开发入门指南1-Visual Studio环境搭建
  • Live Avatar数字人快速部署:CLI命令行模式批量生成教程
  • 迪文屏K600+数据库读写避坑指南:从指令解析到.DAT文件导出全流程
  • Android NFC卡模拟实战:从零搭建虚拟门禁卡(附完整代码)
  • CogVideoX-2b快速上手:无需代码,网页点一点就能创作视频
  • 内核探秘:四种高效读取进程内存的技术对比与实践
  • nlp_structbert_sentence-similarity_chinese-large 性能实测:不同GPU型号下的推理速度与成本分析
  • Faiss GPU编译实战:解决CUDA error 209与显卡计算能力不匹配问题
  • AI头像生成器优化指南:如何描述才能生成更精准的头像绘图提示词?
  • Vue2如何通过WebUploader实现3D模型文件的目录结构分片断点续传与校验?
  • 请问 Android 中 AsyncTask 是什么及其原理?
  • 从TED演讲到无声电影:火山语音AV-S2ST技术如何改变跨语言内容创作
  • 5个超实用的深度学习开源数据集推荐(附下载链接和实战案例)
  • Mac鼠标滚动卡顿终极解决方案:Mos让你的滚轮丝滑如触控板
  • nRF52 BLE外设开发模板:事件驱动、低功耗、模块化固件骨架
  • weixin247微信小程序的高校党费收缴系统ssm(文档+源码)_kaic
  • weixin248食堂订餐小程序ssm(文档+源码)_kaic
  • YOLO系列算法改进 | 自研篇 | C2PSA融合GSRA几何-语义校正注意力 | 跨模态几何引导与语义对齐双驱动,破解复杂光照与多尺度目标检测难题 | CVPR 2026
  • 基于Matlab Robotic Toolbox的四轴机械臂运动控制仿真