vue里面除了用css写动画,还可以用js写动画,vue的transition中,定义了几个动画钩子
第一个动画钩子:@before-enter
<div id='app'>
<transition
@before-enter='handleBeforeEnter'
>
<div v-if='show'>hello world</div>
</transition>
<button @click='handleClick'>切换</button>
</div> <script>
var vm = new Vue({
el:'#app',
data:{
show:true
},
methods:{
handleClick:function(){
this.show = !this.show;
},
handleBeforeEnter:function(el){
el.style.color='red'
}
}
})
</script>
在vue的transition中,在显示数据前,会自动触发before-enter这个事件,比如上面
第二个动画钩子:@enter
<div id='app'>
<transition
@before-enter='handleBeforeEnter'
@enter='handleEnter'
>
<div v-if='show'>hello world</div>
</transition>
<button @click='handleClick'>切换</button>
</div>
<script>
var vm = new Vue({
el:'#app',
data:{
show:true
},
methods:{
handleClick:function(){
this.show = !this.show;
},
handleBeforeEnter:function(el){
el.style.color='red'
},
handleEnter:function(el,done){
setTimeout(function(){
el.style.color='green';
done();
},2000);
}
}
})
</script>
在执行动画的时候,会触发@enter这个事件,我们大部分动画流程都是写在这里吗,这个事件跟@before-enter,有点不一样的地方就是,多了一个参数done,在执行完后,回调一下done(),告诉vue,动画执行完了,vue好执行下一个钩子函数
第三个钩子函数:@after-enter
<div id='app'>
<transition
@before-enter='handleBeforeEnter'
@enter='handleEnter'
@after-enter='handleAfterEnter'
>
<div v-if='show'>hello world</div>
</transition>
<button @click='handleClick'>切换</button>
</div> <script>
var vm = new Vue({
el:'#app',
data:{
show:true
},
methods:{
handleClick:function(){
this.show = !this.show;
},
handleBeforeEnter:function(el){
el.style.color='red'
},
handleEnter:function(el,done){
setTimeout(function(){
el.style.color='green';
},2000);
setTimeout(function(){
done();
},4000)
},
handleAfterEnter:function(el){
el.style.color='black'
}
}
})
</script>
@after-enter在动画执行完后的处理
同理,有入场动画,就有出场动画
分别是before-leave,leave,after-leave
有了这些基础后,就可以写更复杂的动画效果了,我们可以引入一个库,叫做velocity.js
http://velocityjs.org/
打开velocity的官网,下载下来到本地
栗子:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title></title>
<script src="./vue.js"></script>
<script src="../velocity.js"></script>
</head>
<body>
<div id='app'>
<transition
@before-enter='handleBeforeEnter'
@enter='handleEnter'
@after-enter='handleAfterEnter'
>
<div v-if='show'>hello world</div>
</transition>
<button @click='handleClick'>切换</button>
</div> <script>
var vm = new Vue({
el:'#app',
data:{
show:true
},
methods:{
handleClick:function(){
this.show = !this.show;
},
handleBeforeEnter:function(el){
el.style.opacity=0;
},
handleEnter:function(el,done){
Velocity(el,{
opacity:1
},{
duration:1000,
complete:done
})
},
handleAfterEnter:function(el){
console.log('动画结束')
}
}
})
</script>
</body>
</html>
这里就用了Velocity来实现这个动画效果,通过这个可以写出非常酷炫的动画