VUE3 setup父子传参 或者 父亲调用孩子的函数

9 篇文章 0 订阅

1、父传子

        1.1、父亲代码

<!--父亲-->
<template>

  <!--  1、父亲在组价上写要传的值-->
  <child :info="parentInfo"/>
</template>

<script lang="ts" setup>

import Child from "./child.vue";
const parentInfo = '我是父亲传给孩子的值'

</script>

        1.2、孩子代码

<!-- 孩子-->
<template>
  <div>我是孩子:{{ info }}</div>
</template>

<script lang="ts" setup>
//  1、在孩子上引入defineProps
import { defineProps } from 'vue'

//  2、使用efineProps接收值
defineProps({
  info: {}
})

// 附: 也可以这样接收, 这样取值的时候就是 props.info
const props = defineProps({
  info: {}
})

</script>

2、子传父

        2.1、父亲代码

<!--父亲-->
<template>

  <!--  4、在父组价上写方法接收-->
  <child @sendFromChild="parentGetInfo"/>
</template>

<script lang="ts" setup>

import Child from "./child.vue";

// 5、自定义方法接收
const parentGetInfo = (e) => {
  console.log('e是父亲接收到子组件传过来的参数', e)
}

</script>

         2.2、孩子代码

<!-- 孩子-->
<template>
  <div @click="sendToParent">我是孩子:点我传给父亲</div>
</template>

<script lang="ts" setup>

// 前言,子传父如果只通过组件传参,那么只能子组件触发方法,父组件接收方法并调用方法才能传参
// 1、引入defineEmits
import { defineEmits } from 'vue'

// 2、定义emit, 数组内可以写多个 ['sendFromChild', 'xxxxxx', 'xxxx']
const emit = defineEmits(['sendFromChild'])

const sendToParent = () => {
  // 3、调用方法(去父组件接收)
  emit('sendFromChild', '我是孩子发给父亲的信息')
}

</script>

三、子传父

        3.1、父亲代码

<!--父亲-->
<template>

  <button @click="parentFunction">父亲的按钮</button>

  <!-- 1、在父组件上写ref -->
  <child ref="child"/>
</template>

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

// 2、定义一个变量,变量名一定和上面子组件ref内的一致
const child = ref(null)

// 5、最后父亲就可以调用了
const parentFunction =() => {
  child.value.childFunction()
  console.log(child.value.childInfo, '孩子中的变量')
}

</script>

        3.2、孩子代码

<!-- 孩子-->
<template>
  <div>我是孩子</div>
</template>

<script lang="ts" setup>

import { defineExpose, ref } from 'vue'

// 3、孩子上的函数
const childFunction = () => {
  console.log('我是孩子,被父亲调用触发了')
}
// 3、孩子上的变量
const childInfo = ref("我是孩子里的信息")

// 4、一定要把让父亲调用的函数,或者读取的变量   用defineExpose给暴露出去
defineExpose({
  childFunction,
  childInfo
})

</script>

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值