vue3学习2:vue 的指令v-on,event

1.v-on

作用:如果我们想监听用户的点击, 拖拽, 键盘事件等, 可以使用v-on指令,v-on就是用于绑定事件的,通过 v-on 绑定的事件处理函数,需要在 methods 节点中进行声明。
简写:@

举个栗子

<template>
  <div id="app">
    <a>{{num}}</a>
    <br>
    <button v-on:click="add2">+2</button>
    <p>---------</p>
    <button @click="divide2">/2</button>
    <p>---------</p>
  </div>
</template>

<script>

export default {
  name: 'App',
  data(){
    return{
      num:1,
    }
  },
  methods:{
    add2(){
      this.num+=2
    },
    divide2(){
      this.num=this.num/2
    }
  }
}
</script>

在这里插入图片描述

2 event

v-on 指令所绑定的事件处理函数中,可以接收到事件对象 event。

<template>
  <div id="app">
    <a style="color: blue">{{num}}</a>
    <br>
    <button v-on:click="add2" style="background-color: red">{{key}}</button>
    <p>---------</p>

  </div>
</template>

<script>

export default {
  name: 'App',
  data(){
    return{
      num:1,
      key:'/2'
    }
  },
  methods:{
    add2(event){
      if (event.target.style.backgroundColor=='blue')
      {
        event.target.style.backgroundColor='red'
        this.num+=2
        this.key='/2'
      }
      else {
        event.target.style.backgroundColor='blue'
        this.num=this.num/2
        this.key='+2'
      }
    },

  }
}
</script>

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

3 $event

e v e n t 是 v u e 提 供 的 特 殊 变 量 , 用 来 表 示 原 生 的 事 件 参 数 对 象 e v e n t 。 event 是 vue 提供的特殊变量,用来表示原生的事件参数对象 event。 eventvueeventevent 可以解决事件参数对象 event 被覆盖的问题。

<template>
  <div id="app">
    <a style="color: blue">{{num}}</a>
    <br>
    <button v-on:click="add2(2,$event)" style="background-color: red">{{key}}</button>
    <p>---------</p>

  </div>
</template>

<script>

export default {
  name: 'App',
  data(){
    return{
      num:1,
      key:'+2'
    }
  },
  methods:{
    add2(n,event){
      if (event.target.style.backgroundColor=='blue')
      {
        event.target.style.backgroundColor='red'
        this.num+=n
        this.key='/'
      }
      else {
        event.target.style.backgroundColor='blue'
        this.num=this.num/n
        this.key='+'
      }
    },

  }
}
</script>

4 事件修饰符

v-on:click.prevent 阻止默认行为
v-on:click.stop 阻止事件冒泡
v-on:click.capture 以捕获模式触发当前的事件处理函数
v-on:click.once 绑定的事件只触发1次
v-on:click.self 只有在 event.target 是当前元素自身时触发事件处理函数

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

<编程路上>

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值