拾光记录
218个文档 导航 作者 Gitee
随笔记录4
Hexo博客:基础使用Hexo博客:Next主题Hexo博客:Next进阶使用Hexo博客:Next高级配置
前端知识4
基础知识17
Vue框架19
UniApp14
微信小程序1
Java编程6
Java基础15
SpringBoot31
SpringMVC18
MyBatis9
SpringCloud15
中间件2
数据库4
MySQL13
Redis8
MongoDB10
其他数据库1
Python编程6
Python基础知识Python语法yolo目标检测OpenCV的使用及树莓派平台condauv管理工具
Linux12
Linux常用命令Jar启动脚本VirtualBox安装CentOSVirtualBox安装Ubuntu树莓派安装及使用frp内网穿透ArchLinux:基础系统安装ArchLInux:图形化界面安装ArchLinux:常用软件ArchLinux:深度优化ArchLinux:NiriArchLinux:模块记录
软件工具12
IDEAGitMavenGradleNginx安装Nginx配置JMeter压测OllamaRustFSPicGoVSCodeDocker
创意设计2
Blender:入门知识UI设计基础知识
AI相关9
Claude CodeHermes AgentOpenAI基本使用OpenAI工具调用OpenAI记忆管理OpenAI推理执行OpenAI开发框架Langchainllama.cpp

父子组件通信

父传子:props

<!-- 父组件 -->
<Child :user-info="user" :title="pageTitle" />

<!-- 子组件 -->
<script setup>
const props = defineProps({  
  userInfoObject,  
  titleString
})
</script>

子传父:$emit

<!-- 子组件 -->
<script setup>
const emit = defineEmits(['update''delete'])
const handleClick = () => {
  emit('update', { id1 })
}
</script>

<!-- 父组件监听 -->
<Child @update="handleUpdate" />

兄弟组件通信

事件总线,利用uni-app提供的uni.$emituni.$on,创建一个全局的事件中心

// 组件A
uni.$emit('cart-updated', { count5 })

// 组件B(通常在onLoad中监听)
onLoad() {  
  uni.$on('cart-updated'(data) => {    
    this.cartCount = data.count  
  })
}

// 组件卸载时必须取消监听,否则内存泄漏
onUnload() {  
  uni.$off('cart-updated')
}

跨平台注意:uni.$on/$off/$emit在H5、小程序、App都可用,但小程序中页面卸载后监听依然存在,所以一定要在onUnload中取消

跨级组件通信

如果父组件和孙组件(甚至更深)需要通信,一层层传props会很繁琐。这时可以用Vue3的provideinject

// 祖先组件
import { provide, reffrom 'vue'
const user = ref({ name: '张三' })
provide('user', user)  // 传递响应式对象

// 后代组件
import { inject } from 'vue'
const user = inject('user')
父子组件通信兄弟组件通信跨级组件通信