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和自定义事件实现父子组件间的数据流。

相关推荐
LEE几秒前
Agent 的控制权,为什么正在回到模型手里?
前端·后端
沃夫上校几秒前
跨域这件事,其实浏览器在替你挡刀
前端·后端·nginx
十年一梦惊觉醒3 分钟前
快手视频发布助手,全自动视频发布带货工具
开发语言·前端·javascript
Solara3 分钟前
中文字体子集化实录:3.2MB → 200KB 的完整脚本、踩坑清单与三条反直觉经验
前端·css·架构
超人气王5 分钟前
细说agent心跳机制--agentLoop循环机制中死循环处理,带你进一步了解agent工作底层原理
javascript·人工智能
Htr_18 分钟前
Cortex 使用指南:开源 API 知识层
前端·数据库·人工智能·重构·计算机外设
计算机魔术师20 分钟前
Dario Amodei 发文呼吁 AI 行业放慢前沿速度并公布三步计划
前端
EatFan25 分钟前
前后端分离项目中 Token 到底应该怎么设计?Access Token + Refresh Token 实战
java·前端·后端
dsyyyyy110132 分钟前
Typescript装饰器
前端·javascript·typescript
一拳不是超人2 小时前
一个没测暗色模式的 Bug,吃掉了我一半 谷歌扩展用户
前端·javascript·程序员