vue3 transition-group详解
transition-group组件是一个非常有用的工具,可以在Vue应用中实现过渡效果。它可以将多个元素包含在一个动态列表中,并在元素之间进行过渡。上一章我们讲了 transition的基本用法,本章将会讲解transition-group,transition和animate组件库的配合使用还有关于平移过渡动画的案例
一、transition-group
<transition-group> 是一个内置组件,用于对 v-for 列表中的元素或组件的插入、移除和顺序改变添加动画效果
遵循步骤
- 将需要过渡的元素放入transition-group组件内部。
- 使用v-for指令遍历数据列表,并为每个元素设置
唯一的key属性。 - 定义过渡效果的样式
<template>
<button @click="addBox">增加盒子</button>
<transition-group
tag="div"
class="box-wrap"
enter-active-class="animate__animated animate__bounceIn"
leave-active-class="animate__animated animate__bounceOut"
>
<div
v-for="item in boxList"
:key="item.id"
:style="{ backgroundColor: item.bgColor }"
class="box"
></div>
</transition-group>
</template>
<script setup lang="ts">
import { ref, reactive } from "vue";
const boxList = reactive([
{
id: 1,
bgColor: "#666666",
},
]);
const addBox = () => {
boxList.push({
id: boxList.length + 1,
bgColor: color16(),
});
};
const color16 = () => {
const r = Math.floor(Math.random() * 256);
const g = Math.floor(Math.random() * 256);
const b = Math.floor(Math.random() * 256);
const color = `#${r.toString(16)}${g.toString(16)}${b.toString(16)}`;
return color;
};
</script>
<style scoped lang="scss">
.box-wrap {
display: flex;
align-item: center;
justify-content: space-between;
}
.box {
width: 200px;
height: 200px;
margin: 10px;
}
</style>
在上面案例中,首先需要安装animate.css组件库
npm install animate.css --save
其中tag指定一个元素作为容器元素来渲染,其余用法和animate一致。需要注意的是,使用animate.css组件库类名时前面需要加上animate__animated才会生效。
效果图
二、平移过渡动画
<template>
<button class="btn" @click="changeNumber">改变顺序</button>
<transition-group tag="div" class="box-wrap" name="list">
<div class="box" v-for="item in numList" :key="item.id">
{{ item.num }}
</div>
</transition-group>
</template>
<script setup lang="ts">
import { ref, reactive, toRef } from "vue";
import _ from "lodash";
const nums = new Array(81).fill(undefined).map((item, index) => {
return {
id: index,
num: (index % 9) + 1,
};
});
let numList = toRef(nums);
const changeNumber = () => {
numList.value = _.shuffle(numList.value);
};
</script>
<style scoped lang="scss">
.btn {
margin-bottom: 16px;
}
.box-wrap {
display: flex;
flex-wrap: wrap;
width: calc(30px * 9 + 10px);
border-right: 1px solid #ddd;
border-bottom: 1px solid #ddd;
}
.box {
display: flex;
align-items: center;
justify-content: center;
width: 30px;
height: 30px;
border-left: 1px solid #ddd;
border-top: 1px solid #ddd;
}
.list-move {
/* 对移动中的元素应用的过渡 */
transition: all 1s;
}
</style>
上面代码中用到lodash的shuffle方法实现打乱集合效果
npm i --save lodash
效果图:
三、总结
transition和animate组件库结合为Vue应用添加出色的过渡效果,提升用户体验。无论是创建任务列表、图片轮播还是其他场景,transition-group都是一个必备的工具。
2700

被折叠的 条评论
为什么被折叠?



