v-on事件对象,事件修饰符,按键修饰符

278 阅读1分钟

vue事件处理函数中, 拿到事件对象

语法

  • 无传参, 通过形参直接接收
  • 传参, 通过$event指代事件对象传给事件处理函数

示例

<template>
  <div>
    <a @click="one" href="http://www.baidu.com">阻止百度</a>
    <hr>
    <a @click="two(10, $event)" href="http://www.baidu.com">阻止去百度</a>
  </div>
</template>

<script>
export default {
  methods: {
    one(e){
      e.preventDefault()
    },
    two(num, e){
      e.preventDefault()
    }
  }
}
</script>

事件修饰符

语法

<标签 @事件名.修饰符="methods里函数" />

  • .stop - 阻止事件冒泡
  • .prevent - 阻止默认行为
  • .once - 程序运行期间, 只触发一次事件处理函数

示例

<template>
  <div @click="fatherFn">
    <!-- vue对事件进行了修饰符设置, 在事件后面.修饰符名即可使用更多的功能 -->
    <button @click.stop="btn">.stop阻止事件冒泡</button>
    <a href="http://www.baidu.com" @click.prevent="btn">.prevent阻止默认行为</a>
    <button @click.once="btn">.once程序运行期间, 只触发一次事件处理函数</button>
  </div>
</template>

<script>
export default {
  methods: {
    fatherFn(){
      console.log("father被触发");
    },
    btn(){
      console.log(1);
    }
  }
}
</script>

按键修饰符

作用

给键盘事件, 添加修饰符, 增强能力

语法

示例

<template>
  <div>
    <input type="text" @keydown.enter="enterFn">
    <hr>
    <input type="text" @keydown.esc="escFn">
  </div>
</template>

<script>
export default {
 methods: {
   enterFn(){
     console.log("enter回车按键了");
   },
   escFn(){
     console.log("esc按键了");
   }
 }
}
</script>