【vue3】父子组件传值,子组件暴露事件给父组件

一、父传子

defineProps


//父组件
<template>
    <div>父级</div>
    <span>========================================</span>
    <Com :title="'小星星'"></Com>
</template>

//子组件
<template>
    <div>子组件</div>
    <p>这是父级传递的参数---{{ title }}</p>
</template>

<script setup lang='ts'>
	//接收父组件传递过来的值defineProps,是一个接收props的宏函数
	
	/**js*/
    const props = defineProps({
        title:{
            type:String,
            default:'默认值'
        }
    })
    console.log(props.title)

	/**ts*/
    const props = defineProps<{
        title:string
    }>()
    console.log(props.title)
	
	 /**ts特有的,withDefaults,可以定义默认值 
     * 只能接收defineProps<{...}>()
     */
    withDefaults(defineProps<{
        title:string,
        arr:number []
    }>(),{
        title:'默认值2',
        arr:()=>[]
    })

</script>

二、子传父

defineEmits


//子组件
<button @click="send">给父组件传值</button>

<script setup lang='ts'>

	//js
    const emit = defineEmits(['childClick','childClick2])

	//ts
    const emit = defineEmits<{
        (e:'childClick',name:string,arr:number[]):void,
        (e:'childClick2',name:string,arr:number[]):void,
    }>()
   
    const send = ()=>{
        emit('childClick','yyx',[1,2,3])
    }
</script>

//父组件
<template>
    <div>父级</div>
    <span>========================================</span>
    <Com @child-click="getChildData"></Com>
</template>


三、子组件暴露出方法或数据

defineExpose
在父组件调用时,不能直接在setup中使用,需要在声明周期函数中调用,或者事件中调用


//子组件
<script setup lang='ts'>
    const chilfFun = ()=>{
        console.log('我是子组件里面的一个方法')
    }
    defineExpose({
        name:'child游芸霞',
        chilfFun
    })
</script>

//父组件
<template>
    <div>父级</div>
    <button @click="getFun">点击调用子组件参数和方法</button><br>
    <span>========================================</span>
    <Com ref="comRef" ></Com>
</template>

<script setup lang='ts'>
    import { ref, } from 'vue'
    import Com from '../components/Com.vue'
    
    //const comRef = ref()
    const comRef = ref<InstanceType<typeof Com>>()
    const getFun = ()=>{
        console.log(99999,comRef.value?.name)
        comRef.value?.chilfFun()
    }
</script>
    
  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值