vue3中使用defineProps() 和 defineEmits()实现组件通信

一:defineProps()在vue3中可以实现父子组件通信,组件内部不需要引入defineProps。
案例子组件向父组件传值如下:
1:父组件

<template>
  <div>
    <el-button @click="testClick">测试defineProps</el-button>
    <test-plate :sonTitle="fatherTitle" :sonNum="fatherNum"></test-plate>
  </div>
</template>
<script setup>
import testPlate from './componts/test.vue'
import {ref} from "vue"
const fatherTitle = ref('hello')
const fatherNum = ref(1)
const testClick = ()=>{
  fatherTitle.value = '哈哈哈',
  fatherNum.value = 2
}

2:子组件

<template>
    <div>
        <p>{{props.sonTitle}}---{{props.sonNum}}</p>
    </div>
</template>
<script setup>
 let props = defineProps({
      sonTitle:{
       type:String,//接受的数据类型
       default:'默认参数',//接受默认数据
      },
      sonNum:{
       type:Number,
       default:0
    }})
</script>

当然子组件也可以这样写

let props = defineProps(["sonTitle",'sonNum'])

需要注意的是:子组件只能读取父组件传递过来的数据,无法修改数据

二:defineEmits()接受自定义事件,可以实现子组件给父组件传递数据
具体形式是

// 子组件:创建自定义事件,传递数据
const emit = defineEmits(['自定义事件']);
emit('自定义事件', 数据1, 数据2);
 
// 父组件:绑定自定义事件,接收数据
<组件标签 @自定义事件="函数名"></组件标签>
 
const 函数名 = (参数1, 参数2) => {
  console.log(参数1, 参数2);
}

案例:关闭子组件
1:子组件

<template>
    <div>
        <el-button @click="changeView">点我给父组件传值</el-button>
    </div>
</template>
<script setup>
import { ref } from "vue"
const childView = ref(false)
const $emit = defineEmits(['changeChild'])
const changeView =  ()=>{
    $emit('changeChild',childView)
}
</script>

2:父组件

<template>
  <div>
    <test-plate v-if="showView" @changeChild="changeView"></test-plate>
  </div>
</template>
<script setup>
import testPlate from './componts/test.vue'
import {ref} from "vue"
const showView = ref(true)
const changeView = (val)=>{
  console.log('val===',val)
  showView.value = val.value
}
</script>

子组件使用自定义事件后,父组件中的事件函数会自动执行

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值