最近在Vue项目开发的过程中,接触到了事件对象$event,记录一下。
场景1:获取原生DOM事件的事件对象
在DOM事件的回调函数中传入参数$event,可以获取到该事件的事件对象
<template>
<button @click="getData($event)">按钮</button>
</template>
<script>
export default {
methods:{
getdata(e){
console.log(e);
},
}
}
</script>
当点击button按钮时,可以看到控制台打印出的事件对象
通过该对象自带的一些属性,我们可以避免过多的冗余代码,细化代码。
场景2:事件注册所传的参数(子组件向父组件传值)
在子组件中通过$emit
注册事件,将数据作为参数传入,在父组件中通过$event
接收
父组件:
<template>
<Test @change"showData($event)" />
<h4>{{text}}</h4>
</template>
<script>
import Test from '@/components/Test.vue'
export default {
data(){
return {
text :''
}
}
showData(val){
console.log(val);
this.text = val
},
}
</script>
子组件:
<template>
<button @click="$emit('change', 'hello,world')">按钮</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>
此时当点击按钮,就会将子组件传入的’hello,world’字符串在页面上显示出来