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

文章介绍了Vue中父组件向子组件传递数据的`defineProps`,子组件向父组件发送事件的`defineEmits`,以及子组件暴露方法和数据的`defineExpose`。详细展示了如何在组件间进行有效的双向通信。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一、父传子

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>
    
Vue3父子组件之间的数据递主要有以下几种方式: 1. **props(属性)**:这是最常见的方式,父组件通过`props`向下递数据给子组件父组件创建子组件时,可以在`<child>`标签内定义需要从父组件接收的数据,并设置`v-bind`或简写`:`绑定到对应的 props 上。子组件只能读取props,不能修改,除非父组件显式地允许。 ```html <!-- 父组件 --> <template> <div> <child :message="parentMessage"></child> </div> </template> <script> export default { data() { return { parentMessage: &#39;Hello from Parent&#39; }; }, }; </script> ``` 2. **自定义事件($emit)**:子组件可以通过`$emit`触发一个自定义事件,并将数据作为参数发送给父组件父组件需要监听这个事件并处理接收到的数据。 ```html <!-- 子组件 --> <template> <button @click="$emit(&#39;update:message&#39;, &#39;New message from Child&#39;)"> Send Message </button> </template> <script> export default { methods: { sendMessage() { this.$emit(&#39;update:message&#39;, &#39;Child sent a message&#39;); } } }; </script> ``` 3. **ref(响应式引用)**:适用于更复杂的场景,如双向数据绑定。当子组件需要修改的状态需要回流给父组件时,可以使用`ref`并配合`setup()`函数里的`reactive`或`ref`。 4. **提供自定义计算属性**:如果数据需要经过一定的计算才能得出,父组件可以直接暴露一个计算属性供子组件访问。 5. **Vuex(状态管理)**:对于应用级别的状态管理,可以使用Vuex,它让父子组件共享状态变得更容易。 在实际项目中,选择哪种方式取决于需求的复杂度和性能考虑。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值