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

相关推荐
用户14125016652713 分钟前
一文彻底掌握 ECharts:从配置解读到实战应用
前端
LRH15 分钟前
React 架构设计:从 stack reconciler 到 fiber reconciler 的演进
前端
不一样的少年_18 分钟前
【前端效率工具】:告别右键另存,不到 50 行代码一键批量下载网页图片
前端·javascript·浏览器
golang学习记18 分钟前
从0死磕全栈之Next.js 企业级 next.config.js 配置详解:打造高性能、安全、可维护的中大型项目
前端
1024小神21 分钟前
next项目使用状态管理zustand说明
前端
Asort21 分钟前
JavaScript设计模式(八):组合模式(Composite)——构建灵活可扩展的树形对象结构
前端·javascript·设计模式
刘永胜是我23 分钟前
【iTerm2 实用技巧】解决两大顽疾:历史记录看不全 & 鼠标滚轮失灵
前端·iterm
returnfalse25 分钟前
🔥 解密StreamParser:让数据流解析变得如此优雅!
前端
凉城a26 分钟前
经常看到的IPv4、IPv6到底是什么?
前端·后端·tcp/ip
jserTang32 分钟前
Cursor Plan Mode:AI 终于知道先想后做了
前端·后端·cursor