首页 > 解决方案 > 如何正确删除弹出窗口

问题描述

我有一个简单的 popUp 组件,我在整个应用程序中使用它,它通过在点击时发出事件来调用。弹出窗口有两种类型,成功和危险。成功弹出窗口应在 5 秒后自行消失,单击 x 标志时应关闭危险。目前它的工作方式与我创建它的方式相同,但如果用户创建了多个危险弹出窗口,然后是一个成功,然后又是一个危险,危险一个在 5 秒后消失,而不是成功一个。我怎样才能让我的成功弹出窗口在 5 秒后正确消失?我在这里这样称呼它,但似乎它没有正确删除它们:

if(obj.type === 'success') {
   setTimeout(this.closePopUp, 5000);
  }

这是我的代码:

<template>
  <div class="popUp-wrapper">
    <div
      v-for="item in allItems"
      :key="item.id"
      :class="['popUp', `popUp--type--${item.newPopUpType}`]"
    >
      <div class="popUp-side">
        <p class="exclamation-mark">!</p>
      </div>
      <h5 class="popUp-message">{{item.message}}</h5>
      <div class="popUp-side">
        <p class="closing-x" @click="closePopUp(item)" v-if="item.newPopUpType 
        === 'danger'">X</p>
      </div>
    </div>
  </div>
</template>

<script>

export default {
  data: () => ({
    allItems: []
  }),
  methods: {
    closePopUp(item) {
      const index = this.allItems.indexOf(item);
      this.allItems.splice(index, 1);
    },
    onPopUpCall(obj) {
      var newPopUp = {
        newPopUpType: obj.type,
        message: obj.message,
        id: obj.id
      };

      if(obj.type === 'success') {
        setTimeout(this.closePopUp, 5000);
      }
      this.allItems.push(newPopUp);
    }
  },

  created() {
    this.$root.$on('call-popUp', this.onPopUpCall);
  },
  destroyed() {
    this.$root.$off('call-popUp', this.onPopUpCall);
  }
};
</script>

标签: javascriptvue.js

解决方案


closePopUp需要基于您未提供的代码的 item 参数。

尝试这个:

if(obj.type === 'success') {
    setTimeout(() => this.closePopUp(newPopUp), 5000);
}

推荐阅读