Vue Transition不生效排查:点击切换功能正常但无过渡动画
解决Vue Transition不生效的问题
嘿,我瞅了你的代码,立马发现问题所在了——你还没用上Vue的<Transition>组件呢!而且当前的实现是通过切换class来改变状态,但没给这个class变化加上过渡效果,这就是为啥逻辑正常却看不到动画的原因。下面给你两种可行的解决方案:
方案一:直接用CSS过渡(无需Vue Transition组件)
这种方式适配你当前的class切换场景,不用改太多代码,只需要给目标元素加上过渡属性,再定义不同状态下的样式就行:
修改后的完整代码
<template> <div class="switchery" @click="activate"> <div class="switchery-check" :class="{active: isactive}"></div> </div> </template> <script> export default { data() { return { isactive: false } }, methods: { activate() { this.isactive = !this.isactive } } } </script> <style scoped> .switchery { /* 给开关容器加基础样式 */ width: 60px; height: 30px; background-color: #ccc; border-radius: 15px; cursor: pointer; position: relative; } .switchery-check { /* 默认状态样式 */ width: 26px; height: 26px; background-color: white; border-radius: 50%; position: absolute; top: 2px; left: 2px; /* 关键:添加过渡属性,指定要过渡的属性和动画参数 */ transition: left 0.3s ease; } .switchery-check.active { /* 激活状态的位置偏移 */ left: 32px; } </style>
方案二:使用Vue Transition组件(适合元素插入/移除场景)
如果你确实想用到Vue的<Transition>组件,那需要用v-if或v-show控制元素的显示/隐藏,而不是单纯切换class。比如可以让激活和未激活状态对应两个带唯一key的元素,用Transition包裹实现过渡:
修改后的完整代码
<template> <div class="switchery" @click="activate"> <Transition name="switch"> <div class="switchery-check" v-if="isactive" key="active"></div> <div class="switchery-check" v-else key="inactive"></div> </Transition> </div> </template> <script> export default { data() { return { isactive: false } }, methods: { activate() { this.isactive = !this.isactive } } } </script> <style scoped> .switchery { width: 60px; height: 30px; background-color: #ccc; border-radius: 15px; cursor: pointer; position: relative; overflow: hidden; /* 防止动画元素溢出容器 */ } .switchery-check { width: 26px; height: 26px; background-color: white; border-radius: 50%; position: absolute; top: 2px; } /* Vue Transition自动生成的过渡类 */ .switch-enter-from { left: 2px; } .switch-enter-to { left: 32px; } .switch-leave-from { left: 32px; } .switch-leave-to { left: 2px; } .switch-enter-active, .switch-leave-active { transition: left 0.3s ease; } </style>
关键注意点
- 用CSS过渡时,必须给目标元素加上
transition属性,明确指定要过渡的CSS属性(比如left、transform)和动画时长、缓动函数。 - 用Vue Transition组件时,一定要给切换的元素加上唯一
key,否则Vue会复用元素导致过渡不触发;同时确保通过v-if/v-show控制元素的插入和移除。
内容的提问来源于stack exchange,提问作者user2423718
相关产品推荐
相关产品推荐

