vue 阻止事件冒泡常用的方法

在 Vue 中,阻止事件冒泡有两种常用方法:
1. 使用 `event.stopPropagation()` 方法:
在事件处理函数中,可以通过调用事件对象的 `stopPropagation()` 方法来阻止事件冒泡。例如:
```html
<template>
<div @click="parentClick">
<button @click="childClick">点击我</button>
</div>
</template>
<script>
export default {
methods: {
parentClick() {
console.log('父元素被点击');
},
childClick(event) {
event.stopPropagation();
console.log('子元素被点击');
},
},
};
</script>
```
在这个例子中,当点击按钮时,只会触发 `childClick` 方法,而不会触发 `parentClick` 方法。
2. 使用 Vue 的修饰符 `.stop`:
Vue 提供了一种更简洁的方式来阻止事件冒泡,那就是使用 `.stop` 修饰符。例如:
```html
<template>
<div @click="parentClick">
<button @click.stop="childClick">点击我</button>
</div>
</template>
<script>
export default {
methods: {
parentClick() {
console.log('父元素被点击');
},
childClick() {
console.log('子元素被点击');
},
},
};
</script>
```
在这个例子中,我们在 `@click` 事件上添加了 `.stop` 修饰符,这样就可以阻止事件冒泡,只触发 `childClick` 方法。这种方法更简洁,推荐使用。

常用的vue阻止事件冒泡代码 :

1. @click.stop:在模板中使用,阻止点击事件冒泡。
```
<template>
<div @click.stop="handleClick">
<button>Click me</button>
</div>
</template>
```
2. event.stopPropagation():在方法中使用,阻止事件冒泡。
```
<template>
<div @click="handleClick">
<button @click="handleButtonClick">Click me</button>
</div>
</template>
<script>
export default {
methods: {
handleClick(event) {
console.log('div clicked');
},
handleButtonClick(event) {
event.stopPropagation();
console.log('button clicked');
}
}
}
</script>
```
3. .stop:在指令中使用,阻止事件冒泡。
```
<template>
<div v-on:click.stop="handleClick">
<button>Click me</button>
</div>
</template>
```

猜你喜欢

转载自blog.csdn.net/qq_42751978/article/details/130945593