00.表达式
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <script src="../js/vue.js"></script> </head> <body> <div id="app"> <h1>{{count}}</h1> 通过表达式完成事件操作</br> <button @click="count++">点击</button></br> 通过事件对象</br> <button @click="clickEvent">点击1</button> </div> <script type="text/javascript"> var app=new Vue({ el:"#app", data:{ count:0 }, methods:{ clickEvent:function(event){ this.count++; } } }) </script> </body> </html>
01.事件传参
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <script src="../js/vue.js"></script> </head> <body> <div id="app"> <ul> 事件传参,下面的参数与methods中的参数对应,注意:传事件对象是$event格式 <li v-for="item,index in name" @click="clickEvent(item,index,$event)"> 索引值:{{index}}-----姓名:{{item}} </li> </ul> </div> <script type="text/javascript"> var app=new Vue({ el:"#app", data:{ name:[‘蔡徐坤‘,‘范冰冰‘,‘李晨‘] }, methods:{ clickEvent:function(item,index,event){ alert(index); alert(item); alert(event); } } }) </script> </body> </html>
02.修饰符
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <script src="../js/vue.js"></script> </head> <body> <div id="app"> .stop:阻止冒泡事件向上继续传播 <div class="btnParent" @click=" clickParent"> <!-- 如果去掉.stop,就会产生冒泡,触发两次 --> <button @click.stop="clickEvent">按钮</button> </div> .prevent:阻止默认事件 <!-- 下面代码在没有添加阻止事件前,会发生默认行为(请求服务器失败的代码) --> <form action="" method="post"> <input type="text" name="username" id="" value=""> <input @click.prevent="searchWeather" type="submit" value="提交"> </form> .once:只触发一次 <button @click.once="onceEvent">按钮</button> </div> <script type="text/javascript"> var app=new Vue({ el:"#app", data:{ }, methods:{ clickEvent:function(event){ console.log(‘clickEvent‘); }, clickParent:function(){ console.log("clickParent"); }, searchWeather:function(){ console.log("阻止默认事件"); }, onceEvent:function(){ console.log("只触发一次"); } } }) </script> </body> </html>
03.自定义按键码
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <script src="../js/vue.js"></script> </head> <body> 自定义按键码 <div id="app"> <form action=""> <!-- 只有按回车见才会触发(闪一下) --> <input type="text" @keydown.f1="searchWeather" name="username" value="" > </form> </div> <script type="text/javascript"> // 配置自定义修饰符f1 Vue.config.keyCodes.f1 = 112 var app=new Vue({ el:"#app", data:{ }, methods:{ searchWeather:function(){ console.log("查询天气"); } } }) </script> </body> </html>