Vue中如何在组件挂载后实现元素过渡动画?
解决Vue组件挂载后CSS过渡不生效的问题
你的问题出在:浏览器在组件挂载的首次渲染阶段,会把元素的初始bottom:20%和onMounted中直接修改的bottom:10%合并成最终样式一次性渲染,没有捕捉到样式变化的过程,因此过渡动画不会触发。
下面是几种可行的解决方法:
方法1:使用nextTick等待DOM渲染完成
通过nextTick让浏览器先完成初始DOM的渲染,再修改元素样式,这样就能触发过渡:
<template> <div class="layered-image fit"> <img src="/img/Stars-background.svg" class="img1"/> <img ref="img2" src="/img/Mo-zen.svg" class="img2" /> </div> </template> <script setup> import { ref, onMounted, nextTick } from "vue"; const img2 = ref(null); onMounted(async () => { await nextTick(); img2.value.style.bottom = "10%"; }); </script> <style> .img1 { position: absolute; bottom: 0; left: calc(50% - 400px); } .img2 { position: absolute; bottom: 20%; transition: bottom 2s linear; right: calc(50% - 280px); } .fit { height: 100%; width: 100%; } </style>
方法2:通过CSS类切换实现过渡
定义一个额外的CSS类来控制目标样式,在组件挂载后添加这个类,这种方式更符合Vue的响应式风格:
<template> <div class="layered-image fit"> <img src="/img/Stars-background.svg" class="img1"/> <img ref="img2" src="/img/Mo-zen.svg" class="img2" :class="{ 'move-to-bottom': isMounted }" /> </div> </template> <script setup> import { ref, onMounted } from "vue"; const isMounted = ref(false); onMounted(() => { isMounted.value = true; }); </script> <style> .img1 { position: absolute; bottom: 0; left: calc(50% - 400px); } .img2 { position: absolute; bottom: 20%; transition: bottom 2s linear; right: calc(50% - 280px); } .img2.move-to-bottom { bottom: 10%; } .fit { height: 100%; width: 100%; } </style>
方法3:使用Vue的<Transition>组件(推荐)
如果是更复杂的动画场景,使用Vue官方提供的<Transition>组件是更规范的做法:
<template> <div class="layered-image fit"> <img src="/img/Stars-background.svg" class="img1"/> <Transition name="bottom-transition"> <img v-show="isMounted" src="/img/Mo-zen.svg" class="img2" /> </Transition> </div> </template> <script setup> import { ref, onMounted } from "vue"; const isMounted = ref(false); onMounted(() => { isMounted.value = true; }); </script> <style> .img1 { position: absolute; bottom: 0; left: calc(50% - 400px); } .img2 { position: absolute; bottom: 10%; right: calc(50% - 280px); } .bottom-transition-enter-from { bottom: 20%; } .bottom-transition-enter-active { transition: bottom 2s linear; } .fit { height: 100%; width: 100%; } </style>
以上三种方法都能让过渡动画正常触发,你可以根据自己的场景选择合适的方案。
内容的提问来源于stack exchange,提问作者Jackie
相关产品推荐
相关产品推荐

