删除元素时如何使过渡不透明度起作用?

How to make transition opacity work when element is removed?

您好,我为我的 vue 应用程序制作了以下通知组件,我在其中循环处理来自 vuex 商店的错误和成功消息。我在 3 秒后从阵列中删除它们。但是,这意味着不会应用转换,因为元素已从 DOM 中删除。我怎样才能做到这一点?请帮助我。

<template>
  <div
    id="toast-container"
    class="fixed z-50 top-20 right-3"
  >
    <div
      v-for="(error, index) in errors"
      :key="error+index"
      :class="`${error ? 'opacity-1 visible' : 'opacity-0 invisible'}
      toast toast-error flex items-center transition-opacity`"
    >
      <img
        svg-inline
        src="@/assets/icons/alert_triangle.svg"
        alt="alert icon"
      >
      <div class="pl-2">
        <div class="toast-title">
          Der er sket en fejl!
        </div>
        <div class="toast-message">
          {{ error }}
        </div>
      </div>
    </div>
    <div
      v-for="(message, index) in successMessages"
      :key="message+index"
      :class="`${message ? 'opacity-1 visible' : 'opacity-0 invisible'}
      toast toast-success flex items-center`"
    >
      <img
        svg-inline
        src="@/assets/icons/shield_check.svg"
        alt="alert icon"
      >
      <div class="pl-2">
        <div class="toast-title">
          Succes
        </div>
        <div class="toast-message">
          {{ message }}
        </div>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  name: 'Notifications',
  computed: {
    errors() {
      return this.$store.state.global.errors
    },
    successMessages() {
      return this.$store.state.global.successMessages
    },
  },
  watch: {
    errors: {
      handler() {
        setTimeout(() => {
          this.removeError(0)
        }, 3000)
      },
      deep: true,
    },
    successMessages: {
      handler() {
        setTimeout(() => {
          this.removeSuccessMessage(0)
        }, 3000)
      },
      deep: true,
    },
  },
  methods: {
    removeError(index) {
      this.$store.commit('removeError', index)
    },
    removeSuccessMessage(index) {
      this.$store.commit('removeSuccessMessage', index)
    },
  },
}
</script>

查看专为该用例设计的 https://vuejs.org/guide/built-ins/transition-group.html。基本上用 <TransitionGroup> 包裹整个 v-for 块并定义适当的 CSS 类 就是您需要做的所有事情,<TransitionGroup> 将负责动画元素和移除从 DOM 动画完成后,您只需要从状态 add/remove 项目。