1. 程式人生 > >Vue:關於transition-group過渡動畫,別再踩這個坑了!

Vue:關於transition-group過渡動畫,別再踩這個坑了!

使用transition-group踩到的坑

按照vue的文件和UI圖開開心心的噼裡啪啦的敲程式碼:

  <transition-group class="ys-notices" tag="ul" enter-active-class="animated bounceInLeft" leave-active-class="animated bounceOutRight" >
      <li class="item" v-show="index === currentIndex" v-for="(item,index) in notices" :key=
"item.id"
>
公告:{{item.notice}} </li> </transition-group>

可是,我的媽呀,這是怎樣的情況:
在這裡插入圖片描述

找啊找啊找bug–可是動畫類的bug不好找啊!!

眾裡尋他千百度

鬼知道我花了多長時間才想明白這裡出現的問題在哪的T^T,反正!

千萬要在需要過渡動畫的父元件上加上相對定位,子元件上加上絕對定位!

不然將產生不可預知的神奇的亂七八糟的動畫效果 T_T

加上之後就好看多了!
在這裡插入圖片描述

我恨死這個bug了

很討厭這次出現的bug,所以我要把這個元件的原始碼貼出來,走過路過的可以看看還能改進嗎,感謝

~

Advance:需要先npm install animate.css

<template>
  <transition-group class="ys-notices" tag="ul" enter-active-class="animated bounceInLeft" leave-active-class="animated bounceOutRight" >
      <li class="item" v-show="index === currentIndex" v-for="(item,index) in notices" :key="item.id"
> 公告:{{item.notice}} </li> </transition-group> </template> <script> import animated from 'animate.css' export default { name: "Notice", props:{ notices:{ type: Array, default(){ return [{ id:1, notice:"下單閃電配送,平均20分鐘送達!" },{ id:2, notice:"這是第二條測試資料" },{ id:3, notice:"這是第3條測試資料" },{ id:4, notice:"這是第4條測試資料" }] } } }, data(){ return { timer:null, currentIndex:0 } }, computed:{ }, mounted(){ if(this.notices.length>1){ this.timer = setInterval(this.updateNotices,3000); } }, beforeDestroy(){ this.timer && clearInterval(this.timer); }, methods:{ updateNotices(){ this.notices.push(this.notices.shift()); } } } </script> <style lang="less" scoped> @import url("../../../assets/style/color"); @height:30px; .ys-notices{ position: relative; width: 100%; height: @height; /*overflow-y: hidden;*/ color: @notice-color; font-size:1.4rem; font-weight: 300; background: rgba(216,216,216,0.2); border-radius: 22px; li{ position: absolute; list-style: none; width: 100%; height: 100%; display: flex; align-items: center; justify-content: center; } } </style>