Vue3中父子组件传参

1. 父传子

基本上和Vue2中一样,只是需要用defineProps定义,下面举个例子直观地感受一下。

父组件中

<script setup>
import {reactive, ref} from "vue";
import SonView from "@/components/sonView.vue";

const type=ref('free')

 const obj=reactive({
     age:18,
     content:'内容'
 })
</script>

<template>
<div>
    <son-view :type="type"></son-view>
    <son-view></son-view>  //检验默认值效果
    <son-view :obj="obj"></son-view>
    <son-view v-bind="obj"></son-view> //上一条语句的不同写法
</div>
</template>

<style scoped>

</style>

子组件中

<script setup>
// const props=defineProps(['type'])
const props = defineProps({
    type: {
        type: [Number, String],
        default: 'son'
    },
    // obj:{
    //     type:[Object]
    // }
    obj: [Object],
    age: [Number],//这里把obj里的age单独拿出来了
    content: {
        type: [String],
        default: '默认'
    }
})
</script>

<template>
    <div>
        {{ props.type }}
        {{ props.obj }}
        {{ props.age }}
    </div>
</template>

<style scoped>

</style>

2.子传父

需要用defineEmits,有两种方法,下边是举例。

父组件中,和Vue2一样,自定义一个方法。


<script setup>
function fromSons(data){
    console.log(data)
}
</script>

<templete>
<son-view @fromSon="fromSons"></son-view>
<template>

子组件中,有下面两种方法传参

//方法一
<button @click="$emit('fromSon',{id:123})">子传父</button>

//方法二

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

<script setup>
const emit=defineEmits(['fromSon'])
function toFather(){
    emit('fromSon',{id:456})
}
</script>

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值