vue3中父子组件传值

1、父向子

       在子组件上自定义一个属性,属性名随意 ,属性值是你要传的参数。

<template>
  <div class="home">
    <HelloWorld :index="num" /> //子组件
  </div>
</template>

         然后在子组件代码script标签中,导入definePops 这个方法,定义一个常量props用来接收父组件传过来的值,就可以了。

<script setup>
    import {ref ,defineProps} from "vue";
    const props = defineProps({
        index:{}
       }
</script>
<template>
  <div class="hello">
    <h2>{{ index }}</h2>
  </div>
</template>

2、子向父

在子组件声明一个任意常量,用于定义传输参数的方法,名字自定义。

const emit = defineEmits(["updateNum"]);

同时在子组件中定义一个方法去触发emit这个方法,

emit('updateNum',value) //value是传给父元素事件的参数

 父组件中子组件标签上加一个方法,调用方法参数就是子组件传给父组件的参数

<template>
  <div class="home">
    <HelloWorld @undataNum='getNum' :index="num"  />
  </div>
</template>


<script>
    const getNum =(value)=>{
        console.log(value);//value为传过来的参数
    }
</script>

子向父还有一种方法

在子组件中导入defineExpose方法,把你想要传的参数抛出去

<script setup>
    import { ref, defineProps, inject, defineExpose } from "vue";
    const numPlus = ref(1);
    defineExpose({ numPlus});

</script>

在父组件中子组件的标签上接收ref,名字自定义

   <HelloWorld  :index="num" ref="treeRef" />

然后再页面直接打印就可以了

    console.log(treeRef.value.numPlus); 

  • 5
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值