【问题标题】:List Transitions work only for "enter" not for "leave"列表转换仅适用于“进入”而不适用于“离开”
【发布时间】:2021-07-19 06:13:04
【问题描述】:

the example in the docs 之后,我使用transition-group 作为项目列表。奇怪的是,它在项目出现时起作用(enter),而不是在它们消失时(leave),这意味着它们在出现时以动画方式向下滑动,但在没有动画的情况下立即消失:leave 动画失败。为什么?

<template>
  <div v-if="notifications.length">
    <transition-group name="notifications">
      <span
        v-for="notification in notifications"
        :key="notification.id"
      >
        <!-- content -->
      </span>
    </transition-group>
  </div>
</template>

<script>
import { mapState } from 'vuex'

export default {
  computed: {
    ...mapState({
      notifications: state => state.notifications.notifications
    })
  }
}
</script>

<style lang="scss" scoped>
.notifications-enter-active,
.notifications-leave-active {
  transition: all 0.5s;
}

.notifications-enter {
  transform: translateY(-100%);
}
.notifications-leave-to {
  opacity: 0;
}
</style>

商店

export const mutations = {
  DELETE_NOTIFICATION (state, id) {
    state.notifications.splice(
      state.notifications.findIndex(item => item.id === id),
      1
    )
  }
}

【问题讨论】:

    标签: vue.js transition


    【解决方案1】:

    我无法使用该代码 (demo 1) 重现确切的症状,在您的场景中,它只会在 leave 而不是 enter 上转换。原因是spandisplay: inline,这会阻止转换。

    Vue 文档为此提供了一个提示:

    重要的一点是,这些 FLIP 转换不适用于设置为 display: inline 的元素。作为替代方案,您可以使用 display: inline-block 或将元素放在 flex 上下文中。

    所以,您可以在transition-group 上申请display: flex

    <template>
      <transition-group class="container">
        ...
      </transition-group>
    </template>
    
    <style>
    .container {
      display: flex;
    }
    </style>
    

    demo 2

    display: inline-block 上的span 进行转换:

    <template>
      <span class="notification-item">
        ...
      </span>
    </template>
    
    <style>
    .notification-item {
      display: inline-block;
    }
    </style>
    

    demo 3

    【讨论】:

    • 实际上,如果我只是用&lt;div&gt; 替换我的&lt;span&gt;,情况不会改变,leave 转换仍然不会发生。我想这意味着问题出在其他地方?
    • 你能链接到复制品吗?
    • 我偶然发现了罪魁祸首 - 看看我自己的答案(偶然因为它为什么不起作用真的没有意义)
    【解决方案2】:

    原来用&lt;div v-if="notifications"&gt; 替换&lt;div v-if="notifications.length"&gt; 转换现在可以工作了。尽管这对我没有任何意义。

    如果有人能在评论中解释一下就好了:)

    【讨论】:

    • 假设通知只是一个数组(而不是 null),即使为空,数组也始终为真,因此 v-if="notifications" 将始终计算为 true。它在这里没有任何意义,如果没有它,您的模板也可以正常工作。
    • 我只是再次测试它以防万一:如果我添加.length,转换立即停止工作。如果我删除它,它们会再次工作!
    • 如果不进行复制,这很难解决。如果删除 v-if="notifications" 会发生什么?
    • 好问题,当我删除它时,通知仍然有效。这对我来说很奇怪,因为 Vue 转换应该需要 v-ifv-show 不是吗?
    • 条件渲染只需要在&lt;transition&gt;/&lt;transition-group&gt;的元素within上,v-for满足。你实际上并不需要那个外部的v-if,因为v-for 在一个空数组上或者null 会正确退出。
    猜你喜欢
    • 2021-08-10
    • 2021-08-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-04-20
    • 2012-08-02
    • 2017-07-07
    • 2022-01-03
    相关资源
    最近更新 更多