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

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

在 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

相关文章

Ubuntu 25.04发行版登场:Linux 6.14内核,带来多项技术革新

IT之家 4 月 18 日消息,科技媒体 linuxiac 昨日(4 月 17 日)发布博文,报道称代号为 Plucky Puffin 的 Ubuntu 25.04 发行版正式上线,搭载最新 Linu...

7 款最佳 Linux 桌面发行版,颜值天花板

一、elementary OS二、Deepin三、Pop!_OS四、Manjaro Linux五、KDE Neon六、Zorin OS七、Nitrux OS想必大家都知道三大常用操作系统:Linux、...

2023 年 10 个最佳 Linux 桌面发行版

Linux 操作系统在桌面领域的发展已经不再被忽视,越来越多的用户正在考虑切换到 Linux 上。在 2023 年,我们可以期待更多的 Linux 桌面发行版的推出和发展。这里列举了 10 个最佳的...

vue:组件中之间的传值(vue组件之间传参)

一、父子组件之间的传值----props/$emit1、父组件向子组件传值--props2.子组件想父组件传值-this.$emit('select',item)二、父组件向下(深层)...

Vue3开发极简入门(16):祖孙组件间通信之provide&amp;inject

前文说了Vue的组件间关系,有父子、爷孙、其他关系。例如之前的Father、Son是父子关系,App与Son就是爷孙关系。而props的Son,与emits的Son,就是其他关系。前文的props是父...