<
>

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

2020-07-16 09:35:02 来源:易采站长站 作者:

本篇文章我们将给大家介绍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事件处理的介绍,希望对需要的朋友有所帮助!

暂时禁止评论

微信扫一扫

易采站长站微信账号