Vue父子组件通信代码示例

<!-- ParentComponent.vue -->
<template>
  <div class="father">
    <h3>父组件</h3>
    <h4>我的车:{{ car }}</h4>
    <h4>儿子给的玩具:{{ toy }}</h4>
    <Child :car="car" :getToy="getToy"/>
  </div>
</template>

<script setup lang="ts" name="Father">
import Child from './Child.vue'
import { ref } from "vue";

// 数据
const car = ref('奔驰')
const toy = ref()

// 方法
function getToy(value:string){
  toy.value = value
}
</script>

在父组件中,我们首先引入了子组件 Child。然后,通过 :car=“car” 和 :getToy=“getToy”,我们将父组件的数据 car 和方法 getToy 传递给了子组件。这样,子组件就可以在其内部访问到这些属性和方法。

接下来,让我们看一下子组件向父组件传递事件的部分代码:

<!-- ChildComponent.vue -->
<template>
  <div class="child">
    <h3>子组件</h3>
    <h4>我的玩具:{{ toy }}</h4>
    <h4>父给我的车:{{ car }}</h4>
    <button @click="giveToyToFather">玩具给父亲</button>
  </div>
</template>

<script setup lang="ts" name="Child">
import { ref } from "vue";

const toy = ref('奥特曼')

// 接收父组件传递过来的属性和方法
const { car, getToy } = defineProps(['car', 'getToy']);

// 方法
function giveToyToFather() {
  getToy(toy.value); // 触发父组件的方法,将玩具传递给父组件
}
</script>

首先,让我解释一下defineProps([‘car’,‘getToy’])的含义。在子组件中,defineProps 函数用于声明组件接收的属性,即 props。在这个例子中,[‘car’,‘getToy’] 是一个字符串数组,指定了子组件需要接收的两个属性名:car 和 getToy。通过调用 defineProps([‘car’,‘getToy’]),Vue 3 将会自动将这些属性传递给组件,并在组件中提供对应的响应式数据。

在子组件中,我们首先使用 defineProps([‘car’, ‘getToy’]) 声明了需要接收的属性和方法。然后,通过 const { car, getToy } = defineProps([‘car’, ‘getToy’]);,我们将父组件传递过来的 car 属性和 getToy 方法解构赋值给了子组件中的变量。最后,当点击按钮时,我们调用 giveToyToFather 方法,该方法会触发父组件的 getToy 方法,并将玩具传递给父组件。

这样,就完成了父组件向子组件传递属性值,以及子组件向父组件传递事件的功能。

相关推荐

  1. Vue父子组件通信代码示例

    2024-04-03 13:14:01       41 阅读
  2. Vue3父子组件通信

    2024-04-03 13:14:01       63 阅读
  3. Vue组件通信讲解[父子组件通信]

    2024-04-03 13:14:01       41 阅读
  4. uniapp父子组件通信

    2024-04-03 13:14:01       53 阅读
  5. vue父子组件通信实现模糊搜索功能

    2024-04-03 13:14:01       31 阅读

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-04-03 13:14:01       94 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-04-03 13:14:01       101 阅读
  3. 在Django里面运行非项目文件

    2024-04-03 13:14:01       82 阅读
  4. Python语言-面向对象

    2024-04-03 13:14:01       91 阅读

热门阅读

  1. CachedNetworkImage 在listview 返回页面闪烁问题

    2024-04-03 13:14:01       33 阅读
  2. @QtCore.pyqtSlot() 的用法

    2024-04-03 13:14:01       30 阅读
  3. 排队接水水水水水水

    2024-04-03 13:14:01       32 阅读
  4. kafka broker

    2024-04-03 13:14:01       36 阅读
  5. go root和go path

    2024-04-03 13:14:01       41 阅读
  6. 软件设计原则:组合/聚合复用原则

    2024-04-03 13:14:01       33 阅读
  7. 算法刷题记录 Day33

    2024-04-03 13:14:01       31 阅读
  8. 如何在Windows上安装SSH

    2024-04-03 13:14:01       44 阅读
  9. 数字化营销:电子元器件商城的新战略路径

    2024-04-03 13:14:01       40 阅读