- 将需要做过渡的元素使用
transition
标签包裹,并给其设置name属性 - 定义name-enter进入过渡的开始状态、name-leave-to离开过渡的结束状态、name-enter-active进入过渡生效时的状态、name-leave-avtive离开过渡生效时的状态
<template>
<div>
<button @click="show=!show">切换</button>
<transition name="fade">
<div class="box" v-if="show">好好学习,天天向上</div>
</transition>
</div>
</template>
<script>
export default {
name: "TransitionAndAnimate",
data() {
return {
show: false
}
}
}
</script>
<style scoped>
.box {
width: 200px;
height: 200px;
background-color: red;
color: #fff;
font-size: 20px;
display: flex;
justify-content: center;
align-items: center;
margin: 30px 0 0 30px;
}
.fade-enter, .fade-leave-to {
opacity: 0;
transform: translate(200px, 200px);
}
.fade-enter-active, .fade-leave-active {
transition: all 2s ease-in-out;
}
</style>
动画
- 将需要做动画的元素使用
transition
标签包裹,并给其设置name属性 - 自定义动画特效keyframes
- name-enter-active进入过渡生效时的状态、name-leave-avtive离开过渡生效时的状态
<template>
<div>
<button @click="flag=!flag">切换</button>
<p></p>
<transition name="bounce">
<img :src="pic" alt="" style="width: 200px;height: 300px" v-if="flag">
</transition>
</div>
</template>
<script>
import pic from '@/assets/happy.jpg'
export default {
name: "TransitionAndAnimateTwo",
data() {
return {
pic: pic,
flag: true
}
}
}
</script>
<style scoped>
.bounce-enter-active {
animation: bounce 2s;
}
.bounce-leave-active {
animation: bounce 2s reverse;
}
@keyframes bounce {
0% {
transform: scale(0);
}
50% {
transform: scale(1.5);
}
100% {
transform: scale(1);
}
}
</style>
借助animate.css实现动画效果
- 将
animate.css
拉取到项目中npm install animate.css@3.5 --save
- 在组件中引入
animate.css
- 直接在transition标签中设置进入、离开生效动画类(animate 特效名称)。
<template>
<div>
<button @click="flag=!flag">切换</button>
<p></p>
<transition
enter-active-class="animated tada"
leave-active-class="animated bounceOutRight"
>
<img :src="pic" alt="" style="width: 200px;height: 300px" v-if="flag">
</transition>
</div>
</template>
<script>
import pic from '@/assets/happy.jpg'
import animate from 'animate.css'
export default {
name: "TransitionAndAnimateThree",
data() {
return {
pic: pic,
flag: true,
}
}
}
</script>
<style scoped>
</style>