Vue--事件、按键修饰符

一、事件修饰符

修饰符的作用就是和事件连用,用来决定事件触发或者是阻止事件触发的机制

常用的事件修饰符

1. stop 停止 冒泡

2. prevent  阻止

3. self 被动触发无效

4.once 只触发一次

1.stop

stop停止事件冒泡

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
     <div id="app">
       <div style="width: 400px;height: 400px;background: aqua" @click="grandfather">
         <div style="width: 200px;height: 200px;background: black " @click="father">
           <div style="width: 100px;height: 100px;background: red" @click="child"></div>
         </div>
       </div>
     </div>
</body>
</html>

<script src="../lib/vue.js"></script>
<script>
  const vue = new Vue({
    el:'#app',
    data:{
      msg:'事件修饰符',
    },
    methods:{
      grandfather(){
        console.log('grandfather')
      },
      father(){
        console.log('father')
      },
      child(){
        console.log('child')
      }
    }
  })
</script>

效果如下,当我们点击红色区域的时候,控制台会输出三行,也就是事件冒泡行为,子标签事件会逐级向上触发父级元素的事件

<div style="width: 200px;height: 200px;background: black " @click.stop="father"></div>

在事件click后加.stop,就会阻止该级事件继续向上冒泡

2.prevent

prevent阻止事件的默认行为

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
     <div id="app">
       <a href="https://www.baidu.com" @click="jump">点我跳转到百度</a>
     </div>

</body>
</html>

<script src="../lib/vue.js"></script>
<script>
  const vue = new Vue({
    el:'#app',
    data:{
      msg:'事件修饰符',
    },
    methods:{
      jump(){
        alert("确定跳转到百度?")
      }
    }
  })
</script>

点击触发,alert提示弹窗,点击默认行为确定,即跳转到百度

<a href="https://www.baidu.com" @click.prevent="jump">点我跳转到百度</a>

加入.prevent,点击确定就不会跳转了

3.self

.self      这个事件如果是我自己元素上发生的事件,这个事件不是别人给我传递过来的事件,则执行对应的程序

4.once

事件只触发一次,之后不再触发,直接出效果

二、按键修饰符

enter 回车键

tab     制表

delete 删除

esc     返回

space 空格

up      上

down  下

left      左

right    右

演示

当键盘按键抬起的时候,响应方法

 <div id="app">
      <input type="text" v-model="msg" @keyup="keyup">
  </div>

当键盘按键回车的时

猜你喜欢

转载自blog.csdn.net/m0_63732435/article/details/133295272