vue组件通信系类之父子传参

本文详细介绍了Vue3中父子组件之间的数据传递,通过props实现父传子,通过emits实现子传父,通过实例代码展示了如何在Father组件中将值和方法传递给Son组件以及在Son组件中触发父组件方法的过程。
摘要由CSDN通过智能技术生成

这个系类网上的博客有很多,我就主要和大家分享一下组件通信中父子传参的用法,主要是在一天之内写两篇博客有流量券奖励,我冲了。

在vue3的Father.vue文件中,

<template>

  <Son  :name="name"  :FatherMethods="FatherMethods"/>

</template>

<script  setup>

import  { ref } from 'vue'

import  Son  from '../views/Son.vue'

const name = ref('张三')

const FatherMethods = () =>{

         console.log('我是父组件的方法')

}

</script>

<style scoped>

</style>

在vue3的Son.vue文件中,

<template>

   <h2>父组件传过来的名字:{{ name }}</h2>

</template>

<script  setup>

const props = defineProps({

       name:  String,

       FatherMethods: Function

})

const callFatherMethods = () => {

         props.FatherMethods()

}

</script>

<style scoped>

</ style>

前面是父传子,props(defineProps)的运用,把父组件的值和方法传给子组件,下面探讨emits(defineEmits)的用法,相当于子传父的用法。

在vue3的Father组件中,

<template>

<Son @giveMoney="giveMoney" />

</template>

<script  setup>

import Son from '../views/Son.vue'

const money = ref(0)

const giveMoney = (value) =>{

    money += value

}

</script>

<style  scoped>

</style>

在vue3的Son组件中,

<template>

     <button @click="NeedMoney"></button>

</template>

<script  setup>

  const emits = defineEmits(['giveMoney'])

  const NeedMoney = () =>{

     emits('giveMoney',500)//前面那个是调用的父组件的方法,后面那个是传给那个方法的参数

  }

</script>

<style  scoped>

</style>

       我这里用通俗的语言解释一下emits(defineEmits)的用法,子传父的用法,就是父亲先定义好给钱函数giveMoney()在执行到儿子组件的时候@giveMoney="giveMoney"相当于把父亲组件的给钱函数传给儿子,儿子用defineEmits(['giveMoney'])去接收,此时在儿子组件中定义一个点击事件,触发要钱函数NeedMoney(),NeedMoney()触发父亲传过来的giveMoney()函数,并携带传输传给父亲,让父亲执行给钱函数giveMoney()。

       可能这里和官方的解释有冲突,我只是便于记忆才这样记的,主要想帮大家记住,我刚开始学的时候记了好几次都没记住,就尝试用这种方法记忆。要是和标准不一致,不喜勿喷,狗头保命。

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值