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

一、父传子

defineProps

javascript 复制代码
//父组件
<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

javascript 复制代码
//子组件
<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

javascript 复制代码
//子组件
<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>
    
相关推荐
mCell9 小时前
AI 时代 SVG 画图的潜力
前端·agent·svg
我命由我1234514 小时前
CesiumJS 笔记 - 获取容器中心点、Cartesian3 clone 方法、修改 Cartesian3 对象的高度
前端·javascript·css·前端框架·html·html5·js
Hopebearer_15 小时前
页面突然只剩 DOM?一次静态资源版本错配排查
前端·部署
抱抱宝15 小时前
Agent-study项目教程(03):手写 Mini-ReAct Agent(不依赖框架)
javascript·人工智能·gpt·react.js·prompt·agent
东风破_16 小时前
ESLint 是什么?为什么你的项目需要它?
前端·后端·代码规范
用户9385156350716 小时前
Next.js 笔记系统(二):Redis 数据服务与侧边栏组件拆分实战
javascript·全栈
圣殿骑士-Khtangc17 小时前
Go字符串高效拼接性能对比与底层原理分析
服务器·前端·golang
BigTopOne18 小时前
【ijkplayer】 硬解码流程
前端
kyriewen19 小时前
DeepSeek Harness开源第一天我就上手了——和Claude Code的差距比想象中大
前端·ai编程·deepseek
捡田螺的小男孩19 小时前
什么是 Skill?手把手带你写一个简单有用的 Skill!
前端·后端·程序员