Flash 消息有时不会在 vue2.js 内消失

flash message sometimes does not disappear in vue2.js

我刚刚做了一个闪信组件,从eventBus接收闪信,然后闪现显示3秒消失。组成部分如下:

<template>
  <transition name="fade">
    <div v-if="visible" v-bind:class="type" role="alert">{{ message }}</div>
  </transition>
</template>

<style scoped>
  .fade-enter-active, .fade-leave-active {
    transition: opacity .5s
  }
  .fade-enter, .fade-leave-to {
    opacity: 0
  }
</style>

<script>
  import EventBus from '../../config/EventBus';

  export default {
    name: 'flash-view',
    data() {
      return {
        type: '',
        message: '',
        visible: false,
      };
    },
    mounted() {
      EventBus.subscribeFlashMessage(data => this.setData(data));
      setTimeout(() => (
        this.visible = false
      ), 3000);
    },
    methods: {
      setData(data) {
        this.setType(data.type);
        this.message = data.message;
        this.visible = true;
      },
      setType(type) {
        this.type = `alert alert-${type}`;
      },
    },
  };
</script>

该组件适用于第一条闪现消息,但是如果随后触发闪现消息或者如果我更改路由 (VueRouter),则闪现消息不会消失。我认为这是因为 javascript 被重新触发,这使 setTimeout 的效果无效,但是我不知道如何在 Vue 中解决这个问题。

感谢 Belmin Bedak 的帮助,我已经设法修复了这个错误。现在使用 created() 而不是 mounted() 实现以下内容,因为每个更新周期都会重新触发 mounted。 Created() 设置一次监听器,watch 用于检查可见是否已更改(当新事件被推送到监听器时会发生这种情况)。如果 visible 发生变化,setTimeout 会被正确触发。

<template>
  <transition name="fade">
    <div
      v-if="visible"
      v-bind:class="type"
      role="alert"
      v-text="message"
    >
    </div>
  </transition>
</template>

<style scoped>
  .fade-enter-active, .fade-leave-active {
    transition: opacity .5s
  }
  .fade-enter, .fade-leave-to {
    opacity: 0
  }
</style>

<script>
  export default {
    name: 'flash-view',
    data() {
      return {
        type: '',
        message: '',
        visible: false,
      };
    },
    created() {
      this.$on('flashMessage', data => this.setData(data));
    },
    methods: {
      setData(data) {
        this.type = `alert alert-${data.type}`;
        this.message = data.message;
        this.visible = true;
      },
      setFadeOut() {
        setTimeout(() => (
          this.visible = false
        ), 2500);
      },
    },
    watch: {
      visible: 'setFadeOut',
    },
  };
</script>