阻止默认行为

1
2
3
4
5
6
window.addEventListener("click", function (event) {
// 标准浏览器
event.preventDefault();
// IE浏览器
return false;
});

阻止冒泡

1
2
3
4
5
6
window.addEventListener("click", function (event) {
// 标准浏览器
event.stoppropagation();
// IE浏览器
event.cancelBubble = true;
});

Vue 事件修饰符

Vue.js 为 v-on 提供了事件修饰符。之前提过,修饰符是由点开头的指令后缀来表示的。

事件修饰符 作用
stop 阻止冒泡
prevent 阻止默认行为
once Vue@2.1.4新增,事件执行一次
passive 执行默认方法
capture 事件只作于自身 -去捕获
self 事件只作于自身-不捕获
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35

<template>
<div>
<!-- 阻止单击事件继续传播 -->
<a v-on:click.stop="clickHandlerdoThis"></a>
<!-- 提交事件不再重载页面 -->
<form v-on:submit.prevent="clickHandler"></form>
<!-- 修饰符可以串联 -->
<a v-on:click.stop.prevent="clickHandler"></a>
<!-- 只有修饰符 -->
<form v-on:submit.prevent></form>
<!-- 添加事件监听器时使用事件捕获模式 -->
<!-- 即元素自身触发的事件先在此处处理,然后才交由内部元素进行处理 -->
<div v-on:click.capture="clickHandler">...</div>
<!-- 只当在 event.target 是当前元素自身时触发处理函数 -->
<!-- 即事件不是从内部元素触发的 -->
<div v-on:click.self="doThat">...</div>
<a @click.passive="handlerClick"></a>
</div>
</template>

<script>
import "@/assets/css/reset.css";
import "@/assets/css/common.css";
import "@/assets/css/style.css";
export default {
name: "App",
methods: {
clickHandler(e) {
e.preventDefault();
console.log(e);
},
},
};
</script>

Vue 按键修饰符

keyCode 的事件用法已经被废弃了并可能不会被最新的浏览器支持。使用 keyCode attribute 也是允许的:

| enter |

| |
| |

|

|

|
|

|

|
|

|

|
|

|

|
|

|

|
|

|

|

1
2
3
<template>
<input v-on:keyup.13="submit">
</template>