Vue 提供了 transition 的封装组件,可以给元素和组件添加进入/离开过渡动画:一下情景可以使用
- 条件渲染 (使用 v-if)
- 条件展示 (使用 v-show)
- 动态组件
- 组件根节点
对transition
组件的name
属性自定义,并在css中写入对应的样式
<button @click="flag = !flag">显示或隐藏</button>
<transition name="box">
<div class="box" v-if="flag"></div>
</transition>
.box{
width: 100px;
height: 100px;
background-color: blue;
}
// 进入的过渡动画
// 开始进入
.box-enter-from{
height: 0;
width: 0;
}
// 进入过程
.box-enter-active{
transition: all 2s ease;
}
// 进入结束
.box-enter-to{
height: 100px;
width: 100px;
}
// 离开的过渡动画
// 开始离开
.box-leave-from{
height: 100px;
width: 100px;
transform: rotate(360deg);
}
// 离开过程
.box-leave-active{
transition: all 2s ease;
}
// 离开结束
.box-leave-to{
height: 0;
width: 0;
}
2. 自定义过渡 class 类名
enter-from-class
enter-active-class
enter-to-class
leave-from-class
leave-active-class
leave-to-class
<button @click="flag = !flag">显示或隐藏</button>
<transition
enter-from-class="e-from"
enter-active-class="e-active"
enter-to-class="e-to"
name="fade">
<div class="box" v-if="flag"></div>
</transition>
// 对应的css
.e-from{
height: 0;
width: 0;
}
.e-active{
transition: all 2s ease;
}
.e-to{
height: 100px;
width: 100px;
}
通过自定义class可以 结合css动画库animate css使用
安装库 npm install animate.css -s
在组件中引入 import 'animate.css'
文档 Animate.css | A cross-browser library of CSS animations.
3.transition 8个生命周期
<transition
@before-enter="EnterFrom"
@enter="EnterActive"
@after-enter="EnterTo"
@enter-cancelled="EnterCancel"
@before-leave="LeaveFrom"
@leave="LeaveActive"
@after-leave="LeaveTo"
@leave-cancelled="LeaveCancel"
name="fade">
<div class="shop" v-if="flag"></div>
</transition>
const EnterFrom = (el:Element)=>{
console.log('进入之前');
}
const EnterActive = (el:Element, done:Function)=>{
console.log('进入的过渡曲线');
setTimeout(()=>{
done()
},3000)
}
const EnterTo = (el:Element)=>{
console.log('过渡完成');
}
const EnterCancel = (el:Element)=>{
console.log('执行过渡效果被打断');
}
const LeaveFrom = ()=>{
console.log('离开之前');
}
const LeaveActive = (el:Element, done:Function)=>{
console.log('离开的过渡曲线');
setTimeout(()=>{
done()
},3000)
}
const LeaveTo = (el:Element)=>{
console.log('离开过渡完成');
}
const LeaveCancel = (el:Element)=>{
console.log('离开过渡效果被打断');
}
4. appear
通过这个属性可以设置初始节点的过渡动画,对应三个状态
<transition
appear
appear-active-class=""
appear-from-class=""
appear-to-class=""
name="fade">
<div class="shop" v-if="flag"></div>
</transition>
页可以结合css动画库animate css使用