为什么Vue的Transition组件切换元素时动画没生效?

Mr.海霞 阅读 56

用Transition包裹动态组件切换时动画完全没反应,检查CSS也没问题,这是什么情况啊?

我的代码是这样的:


<template>
  <div>
    <button @click="toggle">切换</button>
    <transition name="fade">
      <component :is="currentView"></component>
    </transition>
  </div>
</template>

<script>
export default {
  data() {
    return {
      currentView: 'ViewA'
    }
  },
  methods: {
    toggle() {
      this.currentView = this.currentView === 'ViewA' ? 'ViewB' : 'ViewA'
    }
  }
}
</script>

我定义了fade-enter-active这些CSS类,但切换时元素直接消失出现,完全没动画效果。试过把transition包裹的元素改成div+v-if结构反而可以,但为什么component动态切换就不行呢?

我来解答 赞 2 收藏
二维码
手机扫码查看
1 条解答
UP主~素伟
你这个问题是因为动态组件切换时,Vue无法正确追踪元素的复用关系。给<component>加个唯一的key属性就能解决。

修改后的代码:
<template>
<div>
<button @click="toggle">切换</button>
<transition name="fade">
<component :is="currentView" :key="currentView"></component>
</transition>
</div>
</template>


加上key后Vue就能正确触发过渡效果了,我踩过这个坑,记得以前调试了好久。
点赞 1
2026-02-19 11:00