Vue中的$event

235 阅读1分钟

vue事件

vue中事件有自定义事件和原生DOM的事件,不同情况下$event所表示的含义不同。

获取原生DOM事件的事件对象

在DOM事件的回调函数中传入参数$event,可以获取到该事件的事件对象

<template>
<button @click="getData($event)">按钮</button>
</template>

<script>
export default {
    methods: {
      getData(e) {
        console.log(e)
      }
    },
}
</script>

image.png

自定义事件所传的参数(子组件向父组件传值)

在子组件中通过$emit注册事件,将数据作为参数传入,在父组件中通过$event接收,父组件同样可以传参。

父组件:

<template>
  <div>
    <Hello @hello="showData($event, '父组件参数')" />
    <div>{{ data }}</div>
    <div>{{ data1 }}</div>
  </div>
</template>

<script>
import Hello from "../../components/Hello.vue";
export default {
  components: {
    Hello,
  },
  data() {
    return {
      data: "",
      data1: "",
    };
  },
  methods: {
    showData(e, type) {
      this.data = e;
      this.data1 = type;
    },
  },
};
</script>

子组件:

<template>
<button @click="$emit('hello', 'hello')">Hello</button>
<!-- $emit()的第一个参数是定义的事件名,第二个参数是要传入的数据 -->
</template>

<script>
export default {

}
</script>

image.png

参考:Vue中的$event详解-CSDN博客