Home >Web Front-end >JS Tutorial >Vue.JS event handling tutorial and code examples
In this article we will introduce to you event processing in vuejs.
Vuejs provides us with a directive called v:on
, which can help us register and listen for dom
events, so that whenever the event is triggered, The method passed to the event will be called.
<strong>v:on</strong>
Syntax of the directive
<!-- v:on:eventname="methodname" --> <button v:on:click="handleClick">Click</button>
In the above code, we listen for ## on the button #click event so that whenever the user clicks on the button, it calls the
handleClick method.
<template> <div> <h1>{{num}}</h1> <button v-on:click="increment">Increment</button> </div> </template> <script> export default{ data:function(){ return{ num:0 } }, methods:{ increment:function(){ this.num=this.num+1 } } } </script>
How to pass parameters to event handlers?
Sometimes event handler methods can also accept parameters.<template> <div> <h1>{{num}}</h1> <!-- 参数10被传递给increment方法--> <button v-on:click="increment(10)">Increment By 10</button> </div> </template> <script> export default{ data:function(){ return{ num:0 } }, methods:{ //参数`value` increment:function(value){ this.num =this.num+value } } } </script>Here, we create an
increment method with only one parameter value to pass the parameters to the
increment(10) method.
How to access the default event object?
To access the default event object in the method vuejs, you need to provide a variable named $event.<template> <!-- 我们正在传递一个$event变量 --> <input placeholder="name" v-on:onchange="handleChange($event)" /> </template> <script> export default{ methods:{ handleChange:function($event){ console.log($event.target.value) } } } </script>Here, we access the event object by using the special $event variable provided by Vuejs. Sometimes we need to access event objects and parameters at the same time.
<template> <!-- 我们传递参数加上$event变量 --> <button v-on:click="hitMe('You hitted me',$event)"> Hit me Hard </button> </template> <script> export default{ methods:{ handleChange:function(message,$event){ $event.preventDefault() console.log(message) } } } </script>
Shorthand syntax
vuejs also provides a shorthand syntax to listen todom events.
<!--简写语法@eventname="method"--> <button @click="handleClick"></button> <!-- 长语法 --> <button v-on:click="handleClick"></button>This article is an introduction to Vue.JS event processing. I hope it will be helpful to friends in need!
The above is the detailed content of Vue.JS event handling tutorial and code examples. For more information, please follow other related articles on the PHP Chinese website!