.stop:阻止事件冒泡
如果我们不想让其事件进行冒泡,可以使用.stop来阻止事件冒泡
<!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 src="https://cdn.jsdelivr.net/npm/vue@2.6.10/dist/vue.js"></script> </head> <body> <!-- 阻止事件冒泡 --> <div id="box"> <div @click="btn2()"> <button @click.stop="btn()">按钮1</button> </div> </div> <script> const box = new Vue({ el: '#box', methods: { btn: function () { console.log('btn被点击了'); }, btn2: function () { console.log('父元素被点击了'); }, } }) </script> </body> </html>
不加.stop时的效果:
加.stop效果时:
. prevent:阻止默认行为
<!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 src="https://cdn.jsdelivr.net/npm/vue@2.6.10/dist/vue.js"></script> </head> <body> <div id="box"> <!-- 阻止默认行为 --> <form action="www.baidu.com"> <button type="submit" @click.prevent="sub">提交</button> </form> </div> <script> const box = new Vue({ el: '#box', methods: { sub() { console.log("提交被阻止") }, } }) </script> </body> </html>
不加.prevent时:
加.prevent时:
同给a链接设置阻止默认行为方法一致。
@keyup.enter:监听键盘回车事件
<!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 src="https://cdn.jsdelivr.net/npm/vue@2.6.10/dist/vue.js"></script> </head> <body> <!-- 阻止事件冒泡 --> <div id="box"> <!-- 监听键盘事件 --> <!-- 这里因为是使用回车来触发键盘事件所以使用@keyup.enter --> <form @submit.prevent=''> <!-- 阻止默认行为发生 --> 账号<input type="text" name="user" /> 密码<input type="text" name="password" @keyup.enter="submit" /> <input type="submit" value="登录" /> </form> </div> <script> const box = new Vue({ el: '#box', methods: { submit(){ console.log('按下了回车'); } } }) </script> </body> </html>
当加了@keyup.enter事件后:按下键盘中的回车键可以不用点击登陆也可以直接提交数据
效果如下: