当前位置:首页 > 技术文章 > 正文内容

Vue3 中,父子组件如何传递参数?(vue父子组件传递数据方法)

zonemu14小时前技术文章1

在 Vue3 中,组件化开发是非常重要的特征,那么组件之间传值就是开发中常见的需求了。组件之间的传值三种方式:父传子、子传父、非父子组件传值。

一、父传子( defineProps )

父组件主要通过使用 props 向子组件传值。

在使用 <script setup> 的单文件组件中,props 可以使用 defineProps() 、defineEmits() 宏来声明:

在父组件( Parent.vue )中,向子组件传值:

<template>

<Child :message="parentMessage" />

</template>

<script setup>

import Child from './Child.vue'

const parentMessage= 'Hello Parent';

</script>


在子组件( Child.vue )中,接收父组件( Parent.vue )的参数:

<template>

<div>{{ message }}</div>

</template>

<script setup>

import { defineProps } from 'vue';

const props = defineProps({

message: String

});

</script>

二、子传父( defineEmits )

在子组件( Child.vue )中,向父组件( Parent.vue )的传值:

<template>

<button @click="setData">Click me</button>

</template>

<script setup>

import { defineEmits } from 'vue';

const emit = defineEmits(['update']);

function setData() {

emit('update', 'Hello Child');

}

</script>


在父组件( Parent.vue )中,接收子组件( Child.vue )的参数:

<template>

{{ messageChild }}

<Child @update="handleMessage" />

</template>

<script setup>

import Child from './Child.vue';

import { ref } from 'vue';

const messageChild = ref('Hello');

function handleMessage(msg) {

messageChild.value = msg;

}

</script>


相关文档链接:

props文档:
https://cn.vuejs.org/guide/components/props.html

相关文章

2020最新门店财务收支管理系统(通用版),直接套用,自动计算

连锁企业的财务不知道怎么做各门店的收支表,不会门店汇总,别着急,看这里,今天小编和大家分享一套2020最新最新门店财务收支系统(通用版),可以快速录入,自动计算,既方便又全面!希望对大家有所帮助!(文...

Linux之父:Linux内核5.8是“我们有史以来最大的发行版之一”

Linux内核负责人Linus Torvalds对Linux内核版本5.8的第一个候选发布版本(rc1)看得出来还是挺满意的,该版本包含80万行新代码行和超过14,000个更改的文件,占内核文件检修的...

2024年10 大 Linux 桌面发行版推荐

年已过半,现在是探究 2024 年最流行的 Linux 发行版的最佳时机。Linux 是一个开源操作系统,构建在 Linux 内核上,并集成了 GNU shell 实用程序、桌面环境、应用程序、包管理...

7种超轻量级的Linux发行版,能够帮助你找到适合自己的操作系统

Linux是一种非常受欢迎的开源操作系统,而且有许多版本可以选择。有时候,你需要一种超轻量级的Linux发行版,它可以在资源有限的设备上运行,并且能够快速启动。本文将介绍7种超轻量级的Linux发行版...

Garuda Linux:现代化、注重性能与美观的Linux发行版

什么是 Garuda Linux?Garuda Linux 是一个基于 Arch Linux 的现代化、注重性能与美观的桌面操作系统。它面向对性能有较高要求的用户,尤其受到 Linux 爱好者、游戏玩...

「图解」父子组件通过 props 进行数据交互的方法

1.组件化开发,经常有这样的一个场景,就是父组件通过 Ajax 获取数据,传递给子组件,如何通过 props 进行数据交互来实现,便是本图解的重点。2.代码的结构3.具体代码 ①在父组件 data 中...