1. 基本使用
transition-group
和 transition
的用法基本上是一样的。
<template>
<div class="content">
<button @click="add">add</button>
<button @click="pop">pop</button>
<div class="wrap">
<!-- 可以给transition-group标签加一个tag="section",将每个div再包一层 -->
<transition-group
leave-active-class="animate__animated animate__hinge"
enter-active-class="animate__animated animate__bounceIn"
>
<div class="item" v-for="item in list" :key="item">{{ item }}</div>
</transition-group>
</div>
</div>
</template>
<script setup lang="ts">
import { reactive, ref } from 'vue';
import 'animate.css'
const list = reactive<number[]>([1, 2, 3, 4, 5, 6])
const add = () => {
list.push(list.length+1)
}
const pop = () => {
list.pop()
}
</script>
<style scoped>
.box {
height: 200px;
width: 200px;
background-color: red;
}
.wrap {
display: flex;
flex-wrap: wrap;
word-break: break-all;
border: 1px solid #ccc;
.item {
margin: 10px;
font-size: 20px;
}
}
</style>
2. 列表的移动过渡
先看一下new Array(81)
和Array.apply(null, {length: 81})
的区别:
Array.apply(null, {length: 81})
可以帮我们初始化好每一项数据,每一项的值都是 undefined
。
过程中,需要使用lodash
库,但是npm install lodash -D
安装之后会有报错,原因是缺少声明文件,需要执行npm install @types/lodash -D
来安装 ts 的声明文件库,lodash
库中的_.shuffle()
方法可以创建一个被打乱值的数组。
<template>
<div class="content">
<button @click="random">random</button>
<transition-group move-class="trans" class="wraps" tag="div">
<div class="items" :key="item.id" v-for="item in list">
{{ item.number }}
</div>
</transition-group>
</div>
</template>
<script setup lang="ts">
import { reactive, ref } from 'vue';
import _ from 'lodash';
let list = ref(Array.apply(null, { length: 81 } as number[]).map((_, index) => {
return {
id: index,
number: (index % 9) + 1
}
}))
console.log(list.value);
const random = () => {
list.value = _.shuffle(list.value);
}
</script>
<style scoped lang="less">
.wraps {
display: flex;
flex-wrap: wrap;
width: calc(25px * 10 + 9px);
.items {
width: 25px;
height: 25px;
border: 1px solid #ccc;
display: flex;
justify-content: center;
align-items: center;
}
}
.trans {
transition: all 5s;
}
</style>
3. 状态过渡
<template>
<div>
<input v-model="num.current" step="20" type="number">
<div>
{{ num.tweenedNumber.toFixed(2) }}
</div>
</div>
</template>
<script setup lang="ts">
import { reactive, ref, watch } from 'vue';
import gsap from 'gsap'
// tweenedNumber是配置项,gsap内部做了num.tweenedNumber = newValue的处理, reactive是默认deep: true,触发响应式
const num = reactive({
current: 0,
tweenedNumber: 0,
})
watch(() => num.current, (newValue, oldValue) => {
gsap.to(num, {
duration: 1, // 1秒
tweenedNumber: newValue,
})
})
</script>
<style scoped lang="less"></style>