Vue+Tailwind删除动画无法在删除前触发的问题求助
Vue Vite + Tailwind CSS 删除动画执行顺序问题解决
问题根源
你当前的代码在点击删除按钮后,立刻触发emit("delete-todo"),父组件会马上移除该子组件,导致删除动画还没开始播放就被销毁了,自然看不到动画效果。必须确保动画完全执行完毕后,再触发组件删除的逻辑。
修复方案
通过监听动画结束事件(animationend)来控制删除时机,这是最可靠的方式(比硬写setTimeout更适配动画时长的变化)。
修改后的完整代码
<script setup> import { computed, ref } from "vue"; const emit = defineEmits(["delete-todo", "edit-todo"]); const props = defineProps({ isSuccess: { type: Boolean, default: false, }, description: { type: String, default: "Nothing", }, id: { type: Number, default: undefined, }, }); const isDelete = ref(false); const description = computed(() => props.description); const checkBox = computed(() => props.isSuccess); const id = computed(() => props.id); function handleDelete() { // 只触发动画,不立即删除 isDelete.value = true; } // 动画结束后触发删除逻辑 function onAnimationEnd(event) { // 确保是删除动画结束才执行(避免其他动画干扰) if (event.animationName === "deletionAnimation") { emit("delete-todo", props.id); } } function handleTest() { isDelete.value = true; } </script> <template> <div class="flex row rounded w-full gap-3 bg-blue-200 p-5" :class="{ del: isDelete }" @animationend="onAnimationEnd" <!-- 新增:监听动画结束事件 --> > {{ id }} {{ isDelete }} <input type="checkbox" class="checkbox my-auto" /> <p class="w-1/2">{{ description }}</p> <button class="btn btn-error" @click="handleDelete">Delete</button> <button class="btn">Edit</button> <button @click="handleTest" class="btn">Test</button> </div> </template> <style> @keyframes deletionAnimation { from { opacity: 1; transform: translateX(0); /* 用transform替代left,性能更好 */ } to { opacity: 0; transform: translateX(500px); } } .del { animation: deletionAnimation 2s ease-in-out; /* 动画结束后保持最终状态,避免组件突然跳回原样 */ animation-fill-mode: forwards; } </style>
关键改动说明
- 移除
handleDelete中的直接emit:点击删除只设置isDelete = true,触发动画类的添加 - 添加
animationend事件监听:在动画完全结束后,再通过emit通知父组件删除该项 - 动画优化:用
transform替代left做位移(CSS transform性能更优),添加animation-fill-mode: forwards让动画结束后保持最终的透明和位移状态,避免视觉跳变 - 动画事件校验:在
onAnimationEnd中判断event.animationName,确保只有删除动画结束时才执行删除逻辑,避免其他可能的动画干扰
补充说明
如果你的父组件在接收delete-todo事件后,是通过从数组中移除对应项来删除组件,那么现在动画会完整播放后,组件才会被销毁,完全符合预期的视觉反馈流程。
内容的提问来源于stack exchange,提问作者anina
相关产品推荐
相关产品推荐

