学习优先度:★★★★☆
难易度:★★★☆☆
Vue.js 中的 v-on 指令用于监听和处理 DOM 事件,如点击、输入更改或按键。
下面的示例演示了如何在 Vue.js 中使用 v-on 来处理按钮点击事件。
【代码示例】
<div id="app">
<!-- v-on:click listens for the click event on the button -->
<button v-on:click="handleClick">Click me!</button>
<p>{{ message }}</p>
</div>
<script>
new Vue({
el: '#app',
data: {
message: 'Hello, Vue!'
},
methods: {
handleClick: function() {
// This method updates the message when the button is clicked
this.message = 'Button clicked!';
}
}
});
</script>
【执行结果】
When you click the button, the message changes from "Hello, Vue!" to "Button clicked!".
v-on 指令允许您将事件监听器直接绑定到 DOM 元素。语法 v-on:click 可简写为 @click。如果指定了事件对象,Vue 会自动将其提供给方法。
【补充】
Vue 支持 .stop、.prevent 和 .capture 等事件修改器,它们可以修改事件的默认行为。例如,v-on:click.stop 阻止事件在 DOM 树中向上传播。