以下是vue动画从入门到跑路目录
对最初的代码——实现点击按钮使文字渐隐渐现的隐藏和显示,进行封装,以下是初始代码
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Vue中的进场和出场过渡</title>
<script src="./vue.js"></script>
<style>
.v-enter,
.v-leave-to{
opacity:0;
}
.v-enter-active,
.v-leave-active{
transition: opacity 1s;
}
</style>
</head>
<body>
<div id="root">
<transition>
<div v-if="show">hello world</div>
</transition>
<button @click="handleClick">切换</button>
</div>
<script >
var vm = new Vue({
el:'#root',
data:{
show:true
},
methods:{
handleClick:function() {
this.show =!this.show
}
}
})
</script>
</body>
</html>
封装后的代码,如下封装好后就可以在需要使用动画的时候使用自己封装好的组件fade进行包裹即可。
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Vue中的css动画组件</title>
<script src="./vue.js"></script>
<style>
.v-enter,
.v-leave-to{
opacity:0;
}
.v-enter-active,
.v-leave-active{
transition: opacity 1s;
}
</style>
</head>
<body>
<div id="root">
<fade :show="show">
<div>hello world</div>
</fade>
<fade :show="show">
<h1>hello</h1>
</fade>
<button @click="handleClick">切换</button>
</div>
<script >
Vue.component('fade',{
props:['show'],
template:`
<transition>
<slot v-if="show"></slot>
</transition>
`
})
var vm = new Vue({
el:'#root',
data:{
show:true
},
methods:{
handleClick:function() {
this.show =!this.show
}
}
})
</script>
</body>
</html>
但有一个问题,除了需要传入参数show之外,还要关联相应的样式,该组件还不够灵活。因此可以使用js动画,不使用css动画。
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Vue中的进场和出场过渡的js组件</title>
<script src="./vue.js"></script>
</head>
<body>
<div id="root">
<fade :show="show">
<div>hello world</div>
</fade>
<fade :show="show">
<h1>hello</h1>
</fade>
<button @click="handleClick">切换</button>
</div>
<script >
Vue.component('fade',{
props:['show'],
template:`
<transition @before-enter="handleBeforeEnter"
@enter="handleEnter">
<slot v-if="show"></slot>
</transition>
`,
methods:{
handleBeforeEnter: function(el){
el.style.opacity = 0;
},
handleEnter: function(el, done){
setTimeout(() => {
el.style.opacity = 1
done()
},1000)
},
}
})
var vm = new Vue({
el:'#root',
data:{
show:true
},
methods:{
handleClick:function() {
this.show =!this.show
}
}
})
</script>
</body>
</html>
虽然这样写比较复杂一点,但是调用的时候就简单很多,而且不依赖外部样式,所以这才是组件比较推荐的写法。