目前为止,过渡动画我们只要是针对单个元素或者组件的:
要么是单个节点;
要么是同一时间渲染多个节点中的一个;
那么如果希望渲染的是一个列表,并且该列表中添加删除数据也希望有动画执行呢?
这个时候我们要使用 <transition-group> 组件来完成;
使用<transition-group> 有如下的特点:
默认情况下,它不会渲染一个元素的包裹器,但是你可以指定一个元素并以 tag attribute 进行渲染;如tag = "p",渲染出来的元素都会包裹到<p>里
<transition-group tag="p" name="why">
过渡模式不可用,因为我们不再相互切换特有的元素;
内部元素总是需要提供唯一的 key attribute 值;
CSS 过渡的类将会应用在内部的元素中,而不是这个组/容器本身;
一、列表过渡的基本使用
我们来做一个案例:
案例是一列数字,可以继续添加或者删除数字;
在添加和删除数字的过程中,对添加的或者移除的数字添加动画;
二、列表过渡的移动动画
在上面的案例中虽然新增的或者删除的节点是有动画的,但是对于哪些其他需要移动的节点是没有动画的:
我们可以通过使用一个新增的 v-move 的class来完成动画;
它会在元素改变位置的过程中应用;
像之前的名字一样,我们可以通过name来自定义前缀;
<template>
<div>
<button @click="addNum">添加数字</button>
<button @click="removeNum">删除数字</button>
<button @click="shuffleNum">数字洗牌</button>
<transition-group tag="p" name="why">
<span v-for="item in numbers" :key="item" class="item">
{{item}}
</span>
</transition-group>
</div>
</template>
<script>
import _ from 'lodash';
export default {
data() {
return {
numbers: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9],
numCounter: 10
}
},
methods: {
addNum() {
// this.numbers.push(this.numCounter++)
this.numbers.splice(this.randomIndex(), 0, this.numCounter++)
},
removeNum() {
this.numbers.splice(this.randomIndex(), 1)
},
shuffleNum() {
this.numbers = _.shuffle(this.numbers);
},
randomIndex() {
// 可以理解 Math.floor()为向下取整
// Math.random() 浮点数0到1之间从0(包括0)往上,但是不包括1(排除1)
return Math.floor(Math.random() * this.numbers.length)
}
},
}
</script>
<style scoped>
.item {
margin-right: 10px;
display: inline-block;
}
.why-enter-from,
.why-leave-to {
opacity: 0;
transform: translateY(30px);
}
.why-enter-active,
.why-leave-active {
transition: all 1s ease;
}
.why-leave-active {
position: absolute;
}
.why-move {
transition: transform 1s ease;
}
</style>
三、列表的交错过渡案例
我们来通过gsap的延迟delay属性,做一个交替消失的动画:
<template>
<div>
<input v-model="keyword">
<transition-group tag="ul" name="why" :css="false"
@before-enter="beforeEnter"
@enter="enter"
@leave="leave">
<li v-for="(item, index) in showNames" :key="item" :data-index="index">
{{item}}
</li>
</transition-group>
</div>
</template>
<script>
import gsap from 'gsap';
export default {
data() {
return {
names: ["abc", "cba", "jiayou", "td", "aaa", "jams"],
keyword:""
}
},
computed: {
showNames() {
// filter() 方法创建一个新的数组,新数组中的元素是通过检查指定数组中符合条件的所有元素。
return this.names.filter(item => item.indexOf(this.keyword) !== -1)
}
},
methods: {
beforeEnter(el) {
//清除筛选框列表的元素显示时调用:第一步
console.log("beforeEnter");
el.style.opacity = 0;
el.style.height = 0;
},
enter(el, done) {
//清除筛选框列表的元素显示时调用:第二步
console.log("enter");
gsap.to(el, {
opacity: 1,
height: "1.5em",
delay: el.dataset.index * 0.5,
onComplete: done
})
},
leave(el, done) {
//筛选开始列表不符合条件的的元素消失时调用
console.log("leave");
gsap.to(el, {
opacity: 0,
height: 0,
delay: el.dataset.index * 0.5,
onComplete: done
})
}
}
}
</script>