Vue 事件处理
一、事件处理
1、使用v-on:xxx 或xxx 绑定事件,其中xxx是事件名
2、methods中函数不能是箭头函数
3、@click="test" 和@click="test($event)"一样,后者能传参
<!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 type="text/javascript" src="../js/vue.js"></script> </head> <body> <div id="container"> <p>Hello, {{name}}</p> <button @click="showInfo($event)">点击</button> </div> <script type="text/javascript"> const vm = new Vue({ el:"#container", data:{ name:"jojo" }, methods:{ showInfo(e){ console.log(e) console.log("methods", this) alert("Hello") } } }) </script> </body> </html>
二、事件修饰符
1、prevent阻止默认事件
2、stop 阻止冒泡事件
3、once 只使用一次,事件只触发一次
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>事件常用修饰符</title> <script type="text/javascript" src="../js/vue.js"></script> <style> .d1{ width: 40px; background-color: aquamarine; } </style> </head> <body> <div id="container"> <!-- prevent --> <a href="https://www.baidu.com/" @click.prevent="showInfo($event)">点击跳转</a> <hr> <!-- stop --> <div class="d1" @click="showInfo"> <button @click.stop="showInfo">点击</button> </div> <!-- once --> <hr> <button @click.once="showInfo">只触发一次</button> </div> <script type="text/javascript"> const vm = new Vue({ el:"#container", methods:{ showInfo(e){ alert("Hello") } } }) </script> </body> </html>
三、键盘事件
1.Vue中常用的按键别名
回车 enter
删除 delete 退格或删除
退出 esc
空格 space
换行 tab 配合 keydown使用
上 up
下 down
左 left
右 right
2、Vue未提供的按键,可以使用原始的key值去绑定,但注意要转为kebab-case(短横线命名)
3、系统修饰符 ctrl shift alt meta 一般配合keydown使用
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>事件处理</title> <script type="text/javascript" src="../js/vue.js"></script> </head> <body> <!-- 1.Vue中常用的按键别名 回车 enter 删除 delete 退格或删除 退出 esc 空格 space 换行 tab 配合 keydown使用 上 up 下 down 左 left 右 right 2、Vue未提供的按键,可以使用原始的key值去绑定,但注意要转为kebab-case(短横线命名) 3、系统修饰符 ctrl shift alt meta 一般配合keydown使用 --> <div id="container"> <!-- <input type="text" placeholder="请输入值" @keydown.tab="showInfo"> --> <input type="text" placeholder="请输入值" @keydown.ctrl="showInfo"> </div> <script type="text/javascript"> const vm = new Vue({ el:"#container", data:{ name:"jojo" }, methods:{ showInfo(e){ console.log(e.target.value) console.log(e.target.value.length) console.log(e.keyCode) } } }) </script> </body> </html>
四、技巧
1、修饰符 可以 连着写
@click.stop.prevent
2、keyup,ctrl +y
<input type="text" placeholder="请输入值" @keydown.ctrl.y="showInfo">

浙公网安备 33010602011771号