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

相关推荐
90后小陈老师15 分钟前
3D个人简历网站 5.天空、鸟、飞机
前端·javascript·3d
chenbin___16 分钟前
react native text 显示 三行 超出部分 中间使用省略号
javascript·react native·react.js
漫路在线4 小时前
JS逆向-某易云音乐下载器
开发语言·javascript·爬虫·python
不爱吃糖的程序媛4 小时前
浅谈前端架构设计与工程化
前端·前端架构设计
BillKu5 小时前
Vue3 Element Plus 对话框加载实现
javascript·vue.js·elementui
郝YH是人间理想6 小时前
系统架构设计师案例分析题——web篇
前端·软件工程
Evaporator Core6 小时前
深入探索:Core Web Vitals 进阶优化与新兴指标
前端·windows
初遇你时动了情6 小时前
html js 原生实现web组件、web公共组件、template模版插槽
前端·javascript·html
QQ2740287567 小时前
Soundness Gitpod 部署教程
linux·运维·服务器·前端·chrome·web3
前端小崔7 小时前
从零开始学习three.js(18):一文详解three.js中的着色器Shader
前端·javascript·学习·3d·webgl·数据可视化·着色器