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

相关推荐
果壳~2 小时前
【前端】【canvas】图片颜色填充工具实现详解
前端
Bigger2 小时前
Tauri (23)——为什么每台电脑位置显示效果不一致?
前端·rust·app
¥懒大王¥2 小时前
XSS-Game靶场教程
前端·安全·web安全·xss
ssshooter2 小时前
为什么移动端 safari 用 translate 移动元素卡卡的
前端·css·性能优化
不会飞的鲨鱼2 小时前
抖音验证码滑动轨迹原理(很难审核通过)
javascript·python
闲云一鹤2 小时前
Claude Code 接入第三方AI模型(MiMo-V2-Flash)
前端·后端·claude
惜.己2 小时前
前端笔记(四)
前端·笔记
小北方城市网2 小时前
第 5 课:Vue 3 HTTP 请求与 UI 库实战 —— 从本地数据到前后端交互应用
大数据·前端·人工智能·ai·自然语言处理
踢球的打工仔2 小时前
ajax的基本使用(上传文件)
前端·javascript·ajax
老华带你飞2 小时前
农产品销售管理|基于springboot农产品销售管理系统(源码+数据库+文档)
数据库·vue.js·spring boot