transition还拥有一个appear属性,作用是让transition标签中元素的动画一上来就立刻执行(下面这个代码块中动画能执行多次,只要一进入就执行)
立即执行动画
<template>
<div class="card">
<transition
name="box"
appear
>
<A v-if="flag"></A>
</transition>
<button @click="flag = !flag">显示/隐藏组件</button>
</div>
</template>
<script setup lang="ts">
import 'animate.css'
import { ref, reactive } from 'vue'
import A from './components/A.vue'
let flag = ref(true)
</script>
<style scoped>
.card {
border: 1px solid black;
}
.box-enter-from{
width:0;
height: 0;
}
.box-enter-active{
transition: all 3s ease;
}
.box-enter-to{
width: 200px;
height: 200px;
}
</style>
- 和普通动画相同,如果不想使用name-enter-from这样的类名,可以通过appear-from-class=""、appear-active-class=""、appear-to-class=""这三个props来指定动画的类名,以更好的和animate.css之类的动画库相结合。需要注意的是以appear-开头的过渡/动画只会在一上来执行一次,之后如果不刷新页面将不再执行
显式指定过渡类名
<template>
<!-- 别忘了加appear -->
<div class="card">
<transition
name="box"
appear
appear-from-class="enter-from"
appear-active-class="enter-active"
appear-to-class="enter-to"
>
<A v-if="flag"></A>
</transition>
<button @click="flag = !flag">显示/隐藏组件</button>
</div>
</template>
<script setup lang="ts">
import 'animate.css'
import { ref, reactive } from 'vue'
import A from './components/A.vue'
let flag = ref(true)
</script>
<style scoped>
.card {
border: 1px solid black;
}
.enter-from{
width:0;
height: 0;
}
.enter-active{
transition: all 3s ease;
}
.enter-to{
width: 200px;
height: 200px;
}
</style>
以下这个代码块中的动画同样只能执行一次,想要再次执行必须刷新页面
结合Animate动画库使用
<template>
<div class="card">
<transition
name="box"
appear
appear-active-class="animate__animated animate__rubberBand"
>
<A v-if="flag"></A>
</transition>
<button @click="flag = !flag">显示/隐藏组件</button>
</div>
</template>
<script setup lang="ts">
import 'animate.css'
import { ref, reactive } from 'vue'
import A from './components/A.vue'
let flag = ref(true)
</script>
<style scoped>
.card {
border: 1px solid black;
}
</style>