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

vue3 两个组件之间传值

Props

父组件可以通过 props 将数据传递给子组件。这是最常见的组件间通信方式

   <!-- 父组件 --><template><ChildComponent :message="parentMessage" /></template><script>import ChildComponent from './ChildComponent.vue';export default {components: {ChildComponent,},data() {return {parentMessage: 'Hello from Parent',};},};</script>
   <!-- 子组件 --><template><div>{{ message }}</div></template><script>export default {props: {message: String,},};</script>

自定义事件 (Emit) 

子组件可以通过 $emit 触发事件将数据传递回父组件。

   <!-- 子组件 --><template><button @click="sendToParent">Send to Parent</button></template><script>export default {methods: {sendToParent() {this.$emit('custom-event', 'Hello from Child');},},};</script>
   <!-- 父组件 --><template><ChildComponent @custom-event="handleEvent" /></template><script>import ChildComponent from './ChildComponent.vue';export default {components: {ChildComponent,},methods: {handleEvent(message) {console.log(message);},},};</script>

Vuex 

Vuex 是 Vue 的状态管理库,可以用来在多个组件间共享状态。

Provide / Inject 

这是一种从祖先组件注入数据到后代组件的方式,而无需逐层传递 props。

Ref 和 Reactive 

使用 Composition API,可以利用 refs 和 reactive 数据来实现组件间的通信。

Event Bus

 虽然在 Vue 3 中,官方推荐使用 Composition API 和其它更现代的通信方式,但在某些情况下,你可能仍然会使用 Event Bus(事件总线)。这通常涉及到创建一个全局事件中心,组件可以通过它发送和接收事件。

   // src/eventBus.jsimport { onMounted, onBeforeUnmount } from 'vue';import mitt from 'mitt';const eventBus = mitt();export default eventBus;
   <!-- 发送方组件 --><script>import eventBus from '@/eventBus';export default {onMounted() {eventBus.on('someEvent', payload => {console.log(payload);});},onBeforeUnmount() {eventBus.off('someEvent');},methods: {triggerEvent() {eventBus.emit('someEvent', 'Hello from Sender');},},};</script>

选择哪种方式取决于你的具体需求和组件层次结构。对于简单的父子组件关系,使用 Props 和自定义事件通常就足够了。对于更复杂的场景,如非父子组件之间的通信,Vuex 或者 Event Bus 可能会更加合适。

http://www.lryc.cn/news/399855.html

相关文章:

  • 基于matlab的深度学习案例及基础知识专栏前言
  • 机器学习——L1 L2 范数 —>L1 L2正则化
  • 大模型时代,还需要跨端framework吗?
  • ASP.NET Core----基础学习05----将数据传递给视图文件的五种情况
  • Flutter实现局部刷新的几种方式
  • 力扣题解(回文子串)
  • 对数的基本概念
  • C双指针滑动窗口算法
  • WPF学习(6) -- WPF命令和通知
  • 升级到LVGL9的一些变化(后续发现再补充)
  • 当在多线程环境中使用 C++进行编程时,怎样确保线程安全以及如何处理线程之间的同步和通信?
  • 博物馆地图导航系统:高精度地图引擎与AR/VR融合,实现博物馆数字化转型
  • liunx作业笔记1
  • 大话C语言:第31篇 指针和数组的关系
  • Mysql-索引应用
  • Facebook 开源计算机视觉 (CV) 和 增强现实 (AR) 框架 Ocean
  • 【接口自动化_13课_接口自动化总结】
  • 安防管理平台LntonCVS视频汇聚融合云平台智慧火电厂安全生产管理应用方案
  • 【Web性能优化】在Vue项目中使用defer优化白屏,秒加载!
  • springboot上传图片
  • python入门:python及PyCharm安装
  • 链接追踪系列-04.linux服务器docker安装elk
  • 深入探讨微服务架构设计模式与常见实践
  • 【java】合并数组的两种方法
  • [图解]分析模式-01-概述1
  • 【网络安全】Oracle:SSRF获取元数据
  • Android Bitmap
  • 2024 年全国青少年信息素养大赛 Python 小学组复赛真题
  • C语言——流程控制:if...else、switch...case
  • 小白的OS Copilot 产品测评