• 技术文章 >web前端 >js教程

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

    藏色散人藏色散人2019-04-01 09:52:17原创874
    本篇文章我们将给大家介绍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事件处理教程及代码示例的详细内容,更多请关注php中文网其它相关文章!

    声明:本文原创发布php中文网,转载请注明出处,感谢您的尊重!如有疑问,请联系admin@php.cn处理
    专题推荐:Vue.JS 事件处理
    上一篇:Vue.js中v-for列表渲染指令的使用(代码示例) 下一篇:nodejs http请求相关的总结介绍
    大前端线上培训班

    相关文章推荐

    • Vue.js框架是什么• Vue.js方法与事件的介绍• 如何理解Vue.js中的条件渲染?(代码示例)• Vue.js中v-for列表渲染指令的使用(代码示例)

    全部评论我要评论

  • 取消发布评论发送
  • 1/1

    PHP中文网