您好,欢迎访问一九零五行业门户网

Vue.JS事件处理教程及代码示例

本篇文章我们将给大家介绍vuejs中的事件处理。
vuejs向我们提供了一个名为v:on的指令,它可以帮助我们注册和侦听dom事件,这样无论何时触发事件,都会调用传递给该事件的方法。
v:on指令的语法
<!-- v:on:eventname="methodname" --><button v:on:click="handleclick">click</button>
在上面的代码中,我们监听按钮上的click事件,以便每当用户单击按钮时,它都会调用handleclick方法。
<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>
如何将参数传递给事件处理程序?
有时事件处理程序方法也可以接受参数。
<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>
这里,我们创建了一个只有一个参数值的increment方法,以便将参数传递给increment(10)方法。
如何访问默认事件对象?
要访问方法vuejs中的默认事件对象,需要提供一个名为$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>
在这里,我们通过使用vuejs提供的特殊$event变量来访问事件对象。
有时我们需要同时访问事件对象和参数。
<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>
简写语法
vuejs还提供了一种简写语法来侦听dom事件。
<!--简写语法@eventname="method"--><button @click="handleclick"></button> <!-- 长语法 --><button v-on:click="handleclick"></button>
本篇文章就是关于vue.js事件处理的介绍,希望对需要的朋友有所帮助!
以上就是vue.js事件处理教程及代码示例的详细内容。
其它类似信息

推荐信息