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


本文摘自PHP中文网,作者藏色散人,侵删。

本篇文章我们将给大家介绍vuejs中的事件处理。

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

v:on指令的语法

1

2

3

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

 

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

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

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

<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>

如何将参数传递给事件处理程序?

有时事件处理程序方法也可以接受参数。

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

<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的变量。

1

2

3

4

5

6

7

8

9

10

11

12

13

14

<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变量来访问事件对象。

有时我们需要同时访问事件对象和参数。

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

<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事件。

1

2

3

4

5

<!--简写语法@eventname="method"-->

<button @click="handleClick"></button>

 

  <!-- 长语法 -->

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

本篇文章就是关于Vue.JS事件处理的介绍,希望对需要的朋友有所帮助!

以上就是Vue.JS事件处理教程及代码示例的详细内容,更多文章请关注木庄网络博客

相关阅读 >>

10+个顶级vue.js工具和库(分享)

vue.js如何做到seo

vue.js怎么改端口号

vue.js图片资源路径不正确怎么办

vue.js的两个核心是什么

vue-cli3.0安装与配置的方法教程(图文)

vue.js基于什么

vue.js和安装有什么区别

vue.js中有多少钩子函数

vue.js路由this.route.push跳转页面不刷新怎么办

更多相关阅读请进入《vue.js》频道 >>




打赏

取消

感谢您的支持,我会继续努力的!

扫码支持
扫码打赏,您说多少就多少

打开支付宝扫一扫,即可进行扫码打赏哦

分享从这里开始,精彩与您同在

评论

管理员已关闭评论功能...

    暂无评论...