vue3中的父传子,子传父

在Vue 3中,父组件向子组件传递数据和子组件向父组件通信的方式与Vue 2非常相似,但Vue 3提供了Composition API和更多的响应式API,为组件间的通信提供了更多的可能性。下面是父传子和子传父的基本方法:

父组件传递数据给子组件

在Vue中,父组件通过`props`向子组件传递数据。

**父组件**:

```html

<!-- ParentComponent.vue -->

<template>

<ChildComponent :someProp="parentData" />

</template>

<script setup>

import { ref } from 'vue';

import ChildComponent from './ChildComponent.vue';

const parentData = ref('这是来自父组件的数据');

</script>

```

**子组件**:

```html

<!-- ChildComponent.vue -->

<template>

<div>{{ someProp }}</div>

</template>

<script setup>

import { defineProps } from 'vue';

const props = defineProps({

someProp: String

});

</script>

```

子组件向父组件通信

子组件向父组件通信一般通过自定义事件来实现。子组件使用`emit`触发事件,父组件监听这个事件。

**子组件**:

```html

<!-- ChildComponent.vue -->

<template>

<button @click="notifyParent">点击我通知父组件</button>

</template>

<script setup>

import { defineEmits } from 'vue';

// 定义emit事件

const emit = defineEmits('customEvent');

const notifyParent = () => {

emit('customEvent', '这是来自子组件的数据');

};

</script>

```

**父组件**:

```html

<!-- ParentComponent.vue -->

<template>

<ChildComponent @customEvent="handleCustomEvent" />

</template>

<script setup>

import { ref } from 'vue';

import ChildComponent from './ChildComponent.vue';

const handleCustomEvent = (data) => {

console.log(data); // "这是来自子组件的数据"

};

</script>

```

总结

  • **父传子**:通过`props`传递数据。父组件在使用子组件的标签时,通过`:属性名="数据"`的形式传递数据给子组件,子组件通过`defineProps`接收数据。

  • **子传父**:通过自定义事件。子组件使用`defineEmits`定义一个事件,然后用`emit`来触发这个事件并可传递数据。父组件在子组件的标签上使用`@事件名="处理函数"`来监听这个事件。

Vue 3的Composition API和响应式API为组件间的通信提供了更灵活的方式,但基本原则仍然是利用props和自定义事件实现父子组件间的数据流。

相关推荐
开开心心就好5 小时前
批量提取PDF中的图片,直接导出原图
前端·javascript·支持向量机·智能手机·pdf·html·启发式算法
Setsuna_F_Seiei7 小时前
前端转型 Agent 开发 05 之 Agent Hooks 与 Checkpointer(让 Agent 从全自动转变人为可掌控)
前端·agent·ai编程
百万蹄蹄向前冲9 小时前
风扇转了一晚上MVP专家团翻车事故
前端·人工智能
默_笙9 小时前
🏛 给 AI 配一间办公室:Harness Engineering 六大模块与它的实现
前端·javascript
linux_cfan11 小时前
videojs v10 源代码系列解读:14 · 谓词守卫:在运行时安全地调用能力
前端·javascript·音视频
kyriewen11 小时前
我扒了 10,221 条 JD:腾讯技术岗 75% 在要 AI
前端·人工智能·ai编程
郑州光合科技余经理12 小时前
同城外卖小程序开发:下单成功后,后台导出能不能对上用户端状态
开发语言·前端·git·后端·uni-app·php·ai编程
+VX:Fegn089512 小时前
计算机毕业设计|基于springboot + vue旅游管理系统(源码+数据库+文档)
java·开发语言·vue.js·spring boot·课程设计
雪芽蓝域zzs12 小时前
第 7 章:双 Y 轴组合图(柱状 + 折线,看板高频场景)
vue.js·echars
IT_陈寒13 小时前
Vue的响应式让我熬到凌晨三点,原来漏了这个小细节
前端·人工智能·后端