vue3父子组件通信---defineProps()、defineEmits()

本文介绍了在Vue3中如何实现父组件向子组件传递数据(通过props)以及子组件向父组件传递数据(通过自定义事件emits)。通过`<scriptsetup>`语法展示了具体的代码实例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

父传子:

父传子:父组件直接把要传递的数据写在子组件标签身上,子组件通过 defineProps 接收父组件传递过来的数据,之后该数据即可在子组件内部使用。

parents:
<script setup>
  import {ref} from 'vue'
  import Child from './Child.vue'

  const res=ref('hello vue3!')
</script>
<templete>
  <h1>我是父组件,我要传递给父组件的数据是{{res}}</h1>
  <Child :parentData="res"></Child>
</templete>
Child.vue:
<script setup>
  defineProps(['parentData'])
</script>
<templete>
  <h2>我是子组件</h2>
  <h5>我的父组件传过来的数据{{parentData}}</h5>
</templete>

子传父:

子传父:在父组件中,也就是子组件的标签身上定义自定义事件,该事件的作用就是接收子组件传递过来的值,然后进行一些操作;在子组件中,通过defineEmits方法,参数是一个数组或者对象,该方法返回一个箭头函数,这个函数需要传递参数,第一个参数是事件类型(事件名称),第二个及以后的参数都表示要传递给父组件的数据

 parent.vue:
<script setup>
import { ref } from 'vue'
import Child from './Child.vue'

const msg = ref('hello world!')

const customHandler = (val) => {
  msg.value = val
}
</script>

<template>
    <h1>我是父组件</h1>
    <pre>我的数据等会要被子组件改变了:{{ msg }}</pre>
    <Child :parentData="msg" @my-event="customHandler"></Child>
</template>

Child.vue
<script setup>
defineProps(['parentData'])
const $emit = defineEmits(['my-event'])
const msg = 'hello vue!'

const handlerClick = () => {
  $emit('my-event', msg)
}
</script>

<template>
    <hr />
    <h2>我是子组件</h2>
    <pre>我是父组件传递过来的数据:{{ parentData }}</pre>
    <h2>点击下方按钮改变父组件的 hello world! 的值</h2>
    <button @click="handlerClick">click me!</button>
</template>

参考来自:https://juejin.cn/post/7234810590875795516
 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值