一、组件自定事件概念
自己定义的事件,包含事件名,事件回调等,定义好之后去给组件使用。也是一种组件的通信方式,适用于子组件传递给父组件。
二、 组件自定义事件实现子传父
1、在父组件中给子组件绑定一个自定义事件
在子组件标签内,通过@事件名=' 事件回调 '
2、子组件需要声明父组件绑定的事件:
在子组件中,通过 const emit=defineEmits(['事件名']) 声明父组件绑定的事件,
通过emit('事件名') 进行触发,传入参数,父组件接受参数
3、子组件触发父组件绑定的事件时,父组件会调用事件回调:
MotherEvent.vue
<template>
<div class="dd">
<div id="df">父组件::欢迎返回子组件数据:<h3>{{sendName}} {{sendTel}}</h3></div>
<!-- 通过父组件给子组件传递函数类型 -->
<Children2 @sendName="re.getName"></Children2>
</div>
</template>
<script setup>
import Children2 from "./Children2.vue"
import {ref,reactive} from 'vue'
const sendName=ref('')
const sendTel=ref('')
//父传子的类型数据
const re = reactive({
getName(name,tel){
sendName.value=name;
sendTel.value=tel;
}
})
</script>
<style>
h3{
color:blueviolet;
}
.dd{
background: goldenrod;
width:50%;
height:400px;
}
#df{
font-size: 32px;
}
</style>
Children2.vue
<template>
<div class="bg">
<p>我是子组件Children</p>
{{emp.name}} 、 {{emp.tel}} <br/><br/>
<el-button @click="emit('sendName',emp.name,emp.tel)">把名字传给父组件</el-button>
</div>
</template>
// 注意:必须使用setup,否则不能渲染
<script setup>
import {ref,computed} from 'vue'
const emp=ref({
name:'张非凡',
tel:'119',
})
//接受父亲传过来的事件
const emit=defineEmits(['sendName'])
</script>
<style>
.bg{
margin: 0 auto;
background: gray;
width:50%;
height:200px;
}
</style>
4、单击子组件的按钮,则可以通过绑定的事件进行参数传递,父组件通过回调接收。