【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


//子组件
<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>
    

你可能感兴趣的:(vue3,javascript,typescript,前端)