【发布时间】:2018-04-08 16:55:12
【问题描述】:
阅读有关事件的 Vue 文档,他们提到了事件修饰符,例如防止或停止。他们在停止时提到:<!-- the click event's propagation will be stopped -->。我假设这将阻止事件冒泡。 prevent 呢。它究竟是做什么的?我假设它会阻止事件被触发两次(例如双击)。这些假设是否正确?我只是在网上找不到更具体的信息。
我读到的:
【问题讨论】:
阅读有关事件的 Vue 文档,他们提到了事件修饰符,例如防止或停止。他们在停止时提到:<!-- the click event's propagation will be stopped -->。我假设这将阻止事件冒泡。 prevent 呢。它究竟是做什么的?我假设它会阻止事件被触发两次(例如双击)。这些假设是否正确?我只是在网上找不到更具体的信息。
我读到的:
【问题讨论】:
.prevent 或 event.preventDefault() - 它停止浏览器的默认行为(例如,当您在 <form> 中点击 <button type="submit"> 时重新加载)
.stop 或 event.stopPropagation() - 它防止事件传播(或“冒泡”)DOM
.once - 事件最多触发一次
【讨论】:
.once
这是 VueJs 2 中的一个实际示例:
var stopEx = new Vue({
el: '#stop-example',
methods: {
elClick: function(event) {
alert("Click from "+event.target.tagName+"\nCurrent Target: "+event.currentTarget.tagName);
}
}
})
#stop-example > div {
max-width: 300px;
min-height: 150px;
border: 2px solid black;
}
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<div id="stop-example">
<h3>without stop propagation</h3>
<div @click="elClick($event)">
<button @click="elClick($event)">Click Me</button>
</div>
<h3>with stop propagation</h3>
<div @click="elClick($event)">
<button @click.stop="elClick($event)">Click Me</button>
</div>
</div>
这是它的工作原理
在第一个 div 元素上,(div) 元素的 (click) 事件由 (div) 和 (div) 的子级处理,因为我们没有停止传播。
因此,一旦您单击按钮,首先触发按钮的单击事件,然后通过移动按钮的祖先来完成冒泡。
目标是处理事件的元素,而 currentTarget 可能是处理事件的元素或元素的祖先。
因此,当您点击第一个(div)上的按钮时,由于处理了父级的点击事件,点击事件会触发两次。
【讨论】: