温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

Vue.JS事件处理的案例

发布时间:2020-12-02 11:11:21 来源:亿速云 阅读:156 作者:小新 栏目:web开发

这篇文章主要介绍Vue.JS事件处理的案例,文中介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们一定要看完!

Vuejs向我们提供了一个名为v:on的指令,它可以帮助我们注册和侦听dom事件,这样无论何时触发事件,都会调用传递给该事件的方法。

v:on指令的语法

<!-- v:on:eventname="methodname" -->

<button v:on:click="handleClick">Click</button>

在上面的代码中,我们监听按钮上的click事件,以便每当用户单击按钮时,它都会调用handleClick方法。

<template>
   <div>
      <h2>{{num}}</h2>
      <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>
       <h2>{{num}}</h2>
       <!-- 参数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事件处理的案例”这篇文章的所有内容,感谢各位的阅读!希望分享的内容对大家有帮助,更多相关知识,欢迎关注亿速云行业资讯频道!

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI