将事件监听器从列表中停止到Vue中的子元素

时间:2018-03-26 21:22:58

标签: vue.js

我正在Vue中创建一个模态,我想在用户点击内部模态容器外部时关闭它。问题是当我在点击父元素时添加一个事件监听器时,所有子元素在点击时也会触发该事件监听器。

我在下面创建了一个简单的演示来演示我的问题。如果用户单击父元素的黑色部分,则模态应该关闭,但子元素的包含空格应该不能触发关闭函数。

new Vue({
  el: '#modal',
  data: {
    active: true,
  },
  methods: {
    closeModal() {
      this.active = false
    }
  }
})
.modal {
  display: none;
  position: fixed;
  top: 0;
  left: 0;
  bottom: 0;
  right: 0;
  justify-content: center;
  align-items: center;
  background-color: black;
}

.modal.active {
  display: flex;
 }

.modal-content {
  width: 200px;
  height: 200px;
  padding: 1rem;
  background-color: white;
 }
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.16/vue.min.js"></script>

<div id="modal" class="modal" :class="{active: active}" v-on:click="closeModal">
  <div class="modal-content">This child element shouldn't be able to close the modal on click.</div>
</div>

3 个答案:

答案 0 :(得分:2)

你可以试试 V系列:click.self = ... 只应在目标元素本身时触发。 希望有所帮助

答案 1 :(得分:1)

我支持 kimy82 的回答。使用click.self。片段已更新。

new Vue({
  el: '#modal',
  data: {
    active: true,
  },
  methods: {
    closeModal(event) {
      this.active = false
    }
  }
})
.modal {
  display: none;
  position: fixed;
  top: 0;
  left: 0;
  bottom: 0;
  right: 0;
  justify-content: center;
  align-items: center;
  background-color: black;
}

.modal.active {
  display: flex;
 }

.modal-content {
  width: 200px;
  height: 200px;
  padding: 1rem;
  background-color: white;
 }
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.16/vue.min.js"></script>

<div id="modal" class="modal" :class="{active: active}" v-on:click.self="closeModal">
  <div class="modal-content">This child element shouldn't be able to close the modal on click.</div>
</div>

答案 2 :(得分:0)

click事件处理程序有事件修饰符 https://vuejs.org/v2/guide/events.html#Event-Modifiers

<!-- modifiers can be chained -->
<a v-on:click.stop.prevent="doThat"></a>