point 1:获取事件对象
在事件的回调函数中传入参数$event,可以获取该事件的事件对象
<template>
<button @click="handler($event)">按钮</button>
</template>
<script>
export default{
methods:{
handler(e){
console.log(e)
}
}
}
</script>
在点击这个按钮时 可以查看控制台打印出的事件对象
point 2 :VUE2通过$emit配合$event,向父组件传参
父组件:在父组件中通过$event
接收
<template>
<Test @change"showData($event)" />
<h3>{{text}}</h3>
</template>
<script>
import Test from '@/components/Test.vue'
export default {
data(){
return {
text :''
}
}
showData(val){
console.log(val);
this.text = val
},
}
</script>
子组件:在子组件中通过$emit
注册事件,将数据作为参数传入,
<template>
<button @click="$emit('change', 'helloWorld')">按钮</button>
<button @click="showData($event)">按钮</button>
<!-- $emit()的第一个参数是定义的事件名,第二个参数是要传入的数据 -->
</template>
<script>
export default {
showData(val){
console.log(val)
this.$emit('change',val)
// 或者这样传递数据
this.$emit('change','hello,world')
}
}
</script>
ponit 3 :vue3 实现自定义事件
因为vue3 是组合式api的写法 所以呢 是没有this的 那么使用this.$emit 来发送事件信息是不可以的。当然vue3就诞生了自己的方法
利用:defineEmits方法返回触发自定义事件---不需要引入,直接使用
子组件的名字---Event
<template>
<div class="child">
<p>我是子组件2</p>
<button @click="handler">点击我触发自定义事件xxx</button>
</div>
</template>
let $emit=defineEmit(['xxx'])
console.log($emit,'asdasdas');
//$emit打印出来是一个箭头函数
//(event, ...args) => instance.emit(event, ...args) 'asdasdas'
//args是一个注入的参数,
const handler = () => {
//第一个参数:事件类型 第二个|三个|N参数即为注入数据
$emit('xxx','东风导弹','航母');
};
父组件--引入 子组件
<template>
<div>
<Event @xxx="handler1" @click="handler2"></Event>
</div>
</template>
<script setup lang="ts">
//引入子组件
import Event from './Event.vue';
//事件回调---1
const handler1 = (param1,param2)=>{
console.log(param1,param2);
}
//事件回调--2
const handler2 = (param1,param2)=>{
console.log(param1,param2);
}
</script>
子组件传递过来的数据直接可以在父组件的子组件部分的回调函数,形参中获取到哦