vue3:setup语法糖,defineProps defineEmits defineExpose 在父子组件之间传递的使用

本文介绍了Vue中用于组件间通信的关键API:defineProps用于定义子组件接收的props,defineEmits用于声明子组件可触发的事件,而defineExpose则用于暴露子组件的方法给父组件调用。通过这些API,父组件能有效地控制和响应子组件的状态变化。
摘要由CSDN通过智能技术生成
1.​defineProps​​​ 用来接收父组件传来的 ​​props​,示例:

子组件:

<template>
  <div>
    <p>{{ message }}</p>
  </div>
</template>
<script setup>
import { difineProps } from 'vue'
difineProps({
    message:{
        type:String,
        default:'我是默认值'
    }
})
</script>

父组件:

<template>
<div>
    <childProps :message="message"></childProps>
</div>
</template>
<script setup>
import childProps from './ChildProps '
import { ref } from 'vue'
const message = ref('我是父组件')
</script>
2.​defineEmits​​​ 子组件向父组件事件传递,示例:

子组件:

<template>
  <div>
    <<button @click="emitEvent">触发事件</button>
  </div>
</template>
<script setup>
import { difineEmits } from 'vue'
const { emit } = difineEmits (['childEvent'])
const emitEvent = ()=>{
    const eventData = 'Data to be passed';
    emit('childEvent', eventData); // 触发自定义事件,并传递数据
}
</script>

父组件:

<template>
<div>
    <child :childEvent="childEvent"></child>
</div>
</template>
<script setup>
import child from './Child '
const childEvent= (data) =>{
    console.log(data)  //输出子组件的值
}
</script>
3.​defineExpose​​​ 组件暴露出自己的属性,在父组件中可以拿到值,示例:

子组件:

<template>
  <div>
    <p>{{ message }}</p>
  </div>
</template>

<script setup>
import { defineProps, defineExpose } from 'vue';

const props = defineProps({
  message: {
    type: String,
    required: true
  }
});

const exposedMethods = {
  getMessage() {
    return props.message;
  }
};

defineExpose(exposedMethods);
</script>

父组件:

<template>
  <div>
    <h3 @click="isclick">我是父组件</h3>
    <child ref="child"></child>
  </div>
</template>

<script setup>
  import child from './child'
  import { ref } from 'vue'
  const child= ref()
  const isclick= () => {
    console.log('接收子组件暴漏出来的方法',child.value.exposedMethods.getMessage)
  }
</script>

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值