Vue.js学习——事件修饰符

Event modifier Vue事件修饰符

在事件处理程序中调用event.preventDefault() 或 event.stopPropagation() 是非常常见的需求。
尽管我们可以在方法中轻松实现这点,但更好的方式是:
方法只有纯粹的数据逻辑,而不是去处理 DOM 事件细节。
为了解决这个问题,Vue.js 为 v-on 提供了事件修饰符。之前提过,修饰符是由点开头的指令后缀来表示的。

.stop:阻止单击事件继续传播

  1. 在html:

.prevent:提交事件不再重载页面

  1. 在html:
    <div id="app" style="position:absolute;top: 100px;left: 100px;">
        <form v-on:submit.prevent="onSubmit">
            <input type="text">
            <input type="submit">
        </form>
      </div>
    
    
  2. 在js:
new Vue({
          el:"#app"
      })

提交表单后页面不会重载

.once:事件只能点击一次

<div id="app" style="position:absolute;top: 100px;left: 100px;">
    <button type="button" class="btn btn-info" @click.once = "add">加1岁</button>
    <h2>{{age}}</h2>
  </div>
    <script>
      new Vue({
          el:"#app",
          data:{
              age:18
          },
          methods:{
              add:function(){
                  this.age++;
              }
          }
      })
    </script>

.capture事件修饰符的作用添加事件侦听器时使用事件捕获模式

  1. html
     <div id="app">
          <div class="parent" @click.capture="parent">parent
              <div class="child" @click="child">child
                  <div class="grandson" @click="grandson">grandson</div>
              </div>
          </div>
      </div>
    
    
  2. css
    .parent{
                width: 200px;
                height: 200px;
                background-color: red;
            }
            .child{
                   width: 100px;
                   height: 100px;
                   background-color: yellow;
            }
            .grandson{
                width: 50px;
                height: 50px;
                background-color: green;
            }
    
    
  3. js
    new Vue({
              el:"#app",
             methods:{
                 parent:function(){
                     console.log("parent")
                 },
                 child:function(){
                     console.log("child")
                 },
                 grandson:function(){
                     console.log("grandson")
                 }
             }
          })
    
    

点击grandson的时候,弹出的顺序为:parent、grandson、child;
由于parent有修饰符,故而先触发事件,然后就是grandson本身触发,最后冒泡事件。
以此类推:点击child的时候,触发顺序是parent,child,parent有修饰符,先触发。

.self 只点自己身上才运行

<div id="app">
      <div class="parent" @click="parent">parent
          <div class="child" @click.self="child">child
              <div class="grandson" @click="grandson">grandson</div>
          </div>
      </div>
  </div>

点grandson的时候,不能冒泡到child,因为child中有.self的事件修饰符,只有点child的时候,才能打印child

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值