Vue 过渡与动画
Vue 把“状态驱动视图”带进了特效:改数据(ref/响应式变量)→ 视图自动更新,配合
与原生开发的差异:原生特效是“操作元素”,Vue 特效是“改状态”,动画交给
React 同理(react-transition-group / framer-motion);大原则:状态变化触发 DOM 变化,框架负责过渡。
给 v-if/v-show 元素自动加进出场类 - 六个状态类:*-enter-from/active/to、*-leave-*
- 列表用
自动处理增删项动画
HTML
<style> #vueDemo { text-align: center; padding: 20px 0; font-family: sans-serif; } #vueDemo button { padding: 8px 18px; border: none; border-radius: 8px; background: #42b883; color: #fff; cursor: pointer; } .vfade-enter-active, .vfade-leave-active { transition: opacity .4s ease, transform .4s ease; } .vfade-enter-from, .vfade-leave-to { opacity: 0; transform: translateY(20px); } .vbox { width: 260px; margin: 14px auto; padding: 20px; border-radius: 12px; background: #e6f7ef; color: #213547; } </style> <div id="vueDemo"> <button id="vToggle">切换显示状态</button> <div id="vBox" class="vbox">🍏 Vue 风格过渡:状态驱动,类自动加</div> </div> <script> // Vue 原生: <Transition name="vfade"><div v-if="show">…</div></Transition> // 等价原生实现,演示 Transition 的六个状态类如何运作 var show = true, box = document.getElementById('vBox'); document.getElementById('vToggle').addEventListener('click', function () { show = !show; if (show) { // enter: from -> active -> to box.style.display = ''; box.classList.add('vfade-enter-from'); requestAnimationFrame(function () { box.classList.remove('vfade-enter-from'); box.classList.add('vfade-enter-active'); setTimeout(function () { box.classList.remove('vfade-enter-active'); }, 400); }); } else { // leave: -> active -> to box.classList.add('vfade-leave-active', 'vfade-leave-to'); setTimeout(function () { box.classList.remove('vfade-leave-active', 'vfade-leave-to'); box.style.display = 'none'; }, 400); } }); </script>
本节要点Vue 特效 = 状态驱动 + 自动管进出场动画;列表用 TransitionGroup。




