在 Vue.js 中,事件处理是交互性应用程序的核心部分。Vue 提供了简洁的语法来处理 DOM 事件,如点击、输入、键盘事件等。
基本事件处理
在 Vue 模板中,你可以使用 v-on
指令来监听 DOM 事件,并调用 Vue 实例中的方法。v-on
可以简写为 @
。
以下是一个简单的示例,演示了如何监听一个按钮的点击事件:
<template>
<button @click="handleClick">点击我</button>
</template>
<script>
export default {
methods: {
handleClick() {
alert('按钮被点击了!');
}
}
}
</script>
在这个例子中,当按钮被点击时,handleClick
方法会被调用,并弹出一个警告框。
事件修饰符
Vue 还提供了一些事件修饰符,用于简化常见的事件处理逻辑。例如:
.stop
:调用event.stopPropagation()
。.prevent
:调用event.preventDefault()
。.capture
:添加事件监听器时使用 capture 模式。.self
:只当事件在该元素本身(而不是子元素)触发时触发回调。.once
:事件将只会触发一次。
下面是一个使用 .prevent
修饰符的示例,用于阻止表单的默认提交行为:
<template>
<form @submit.prevent="handleSubmit">
<input type="text" v-model="name" placeholder="姓名" />
<button type="submit">提交</button>
</form>
</template>
<script>
export default {
data() {
return {
name: ''
};
},
methods: {
handleSubmit() {
alert('表单已提交,姓名:' + this.name);
}
}
}
</script>
在这个例子中,当表单提交时,.prevent
修饰符会阻止默认的表单提交行为,并调用 handleSubmit
方法。
自定义事件
除了监听 DOM 事件外,Vue 还允许你自定义事件,并在组件之间传递数据。这通常用于父子组件之间的通信。
在子组件中,你可以使用 $emit
方法来触发一个自定义事件,并传递数据给父组件。在父组件中,你可以使用 v-on
或 @
来监听这个自定义事件。
以下是一个简单的示例:
<!-- ChildComponent.vue -->
<template>
<button @click="notifyParent">通知父组件</button>
</template>
<script>
export default {
methods: {
notifyParent() {
this.$emit('custom-event', 'Hello from child!');
}
}
}
</script>
<!-- ParentComponent.vue -->
<template>
<ChildComponent @custom-event="handleCustomEvent" />
</template>
<script>
import ChildComponent from './ChildComponent.vue';
export default {
components: {
ChildComponent
},
methods: {
handleCustomEvent(message) {
alert(message); // 显示 "Hello from child!"
}
}
}
</script>
在这个例子中,当子组件中的按钮被点击时,它会触发一个名为 custom-event
的自定义事件,并传递一条消息给父组件。父组件监听到这个事件后,会调用 handleCustomEvent
方法来处理这个消息。