vue3的uniapp的组件通信
时间: 2025-03-27 16:31:50 浏览: 32
### Vue3 uni-app 组件间通信方式
#### 父子组件通过 Props 和 Events 通信
在 Vue3 中,`uni-app` 框架下的父子组件可以通过 `props` 实现父向子的数据传递,而子组件则可通过 `$emit` 向父组件发送事件。
##### 子组件接收来自父组件的消息并展示:
```html
<!-- Child.vue -->
<template>
<div class="child">
{{ message }}
</div>
</template>
<script setup>
import { defineProps } from 'vue';
const props = defineProps({
message: {
type: String,
required: true
}
});
</script>
```
##### 父组件给子组件传递消息,并监听子组件发出的更新通知:
```html
<!-- Parent.vue -->
<template>
<div class="parent">
<Child :message="msg" @updateMessage="handleUpdate"/>
</div>
</template>
<script setup>
import { ref } from 'vue';
import Child from './Child.vue';
let msg = ref('Hello, child component!');
function handleUpdate(newMsg){
console.log(`Received new message: ${newMsg}`);
}
</script>
```
当子组件想要告知父组件某些状态变化时,可以在适当的时候调用 `$emit()` 方法来触发自定义事件[^1]。
#### 兄弟组件间的通信
对于兄弟组件之间共享数据的需求,通常建议借助于 Vuex 或者 Composition API 提供的状态管理方案。然而,在简单情况下也可以利用共同祖先作为中介来进行间接通讯。
#### 跨层级组件通信
如果存在多层嵌套的情况下需要跨越多个层次进行信息交换,则推荐使用 Provide / Inject 功能。这允许顶层组件向下注入依赖项,使得后代组件能够访问这些资源而不必逐级传递参数。
```javascript
// TopLevelComponent.vue
export default {
provide() {
return {
sharedData: this.sharedState
};
},
};
```
```javascript
// DeepNestedChild.vue
export default {
inject: ['sharedData'],
mounted(){
console.log(this.sharedData);
}
};
```
以上就是在 `Vue3` 的 `uni-app` 应用程序里几种常见的组件间交互模式及其具体实现的例子[^2]。
阅读全文
相关推荐


















