component code
The following is a basic Vue.js component code, which contains different types of event handlers:
<template>
<div>
<!-- 内联事件处理器:点击按钮时调用 increaseCount 方法 -->
<button @click="increaseCount">加 1</button>
<p>计数为: {
{ count }}</p>
<!-- 方法事件处理器:点击按钮时调用 greet 方法 -->
<button @click="greet">打招呼</button>
<!-- 在内联事件处理器中调用方法:点击按钮时调用 say 方法 -->
<button @click="say('你好')">说你好</button>
<button @click="say('再见')">说再见</button>
<!-- 在内联事件处理器中访问事件参数:点击按钮时调用 warn 方法 -->
<button @click="warn('表单目前无法提交。', $event)">提交</button>
<button @click="(event) => warn('表单目前无法提交。', event)">提交</button>
</div>
</template>
<script>
export default {
data() {
return {
count: 0,
name: "Vue.js"
};
},
methods: {
// 方法事件处理器:打招呼方法
greet(event) {
alert(`你好 ${this.name}!`);
if (event) {
alert(event.target.tagName);
}
},
// 在内联事件处理器中调用方法:接收消息参数并弹出提示框
say(message) {
alert(message);
},
// 在内联事件处理器中访问事件参数:阻止默认提交行为并弹出警告
warn(message, event) {
if (event) {
event.preventDefault();
}
alert(message);
},
// 内联事件处理器:增加计数方法
increaseCount() {
this.count++;
}
}
};
</script>
Inline event handler
Inline event handlers are a simple and straightforward way of handling events. In the above code, we use @click
or v-on:click
to listen to the click event of the button and call the corresponding method. For example, @click="increaseCount"
it means calling the method to increment the count when a button is clicked increaseCount
.
method event handler
When event handling logic becomes more complex, method event handlers can be used. In the above code, we define the greet
, say
, warn
, and increaseCount
methods, and then @click
directly reference these methods through . This makes the code more modular and easier to maintain.
Event parameters and modifiers
Vue.js allows us to access native DOM events and their parameters. For example, through $event
variables, we can warn
access native DOM events in methods and prevent their default behavior. At the same time, Vue.js provides event modifiers, such as .stop
, .prevent
, .self
etc., to simplify common requirements for event processing.