vue2.0 中使用transition实现动画效果使用心得

2020-06-13 10:32:37易采站长站整理

先看下demo效果:

这里写图片描述

其实就是个简单的todo lists的小demo,可以看到,当其中一个元素过渡的时候,会影响其他元素的过渡。当然,删除按钮其实本身也是一个transition过渡,也就是说可以在transition-group里使用transition,看下相关代码:


<template>
<div class="app">
<button @click="add" class="add-btn">+</button>
<transition-group name="slide" tag="ul" class="list-wrapper">
<li class="list" v-for="(item, index) in lists" v-touch:swipeleft="showBtn.bind(this, index)" v-touch:swiperight="hideBtn.bind(this, index)" :key="item">
<span class="text">{{item.text}}</span>
<transition name="move">
<button class="del-btn" @click="delList(index)" v-show="item.show">删除</button>
</transition>
</li>
</transition-group>
</div>
</template>

有个小坑的地方就是,之前看官网列表过渡的栗子,它是一个数组,元素都是数字,并且每一项都必须设置唯一的key值。所以我完成demo的时候就自作聪明地将索引值传给key,结果过渡老是不对,后来换成对应的item就正常了(生无可恋脸)。这个demo用到了vue-touch,虽然github上说不支持2.0版本了,但是有一个next分支是支持的,只需在项目下安装它即可:

sudo npm install --save git: //github.com/vuejs/vue-touch.git#next

这里看下主要的样式:


.list
display: flex
width: 100%
height: 40px
line-height: 40px
margin-bottom: 10px
color: #666
font-size: 14px
background: #eee
transition: all .4s
&.slide-move
transition: transform 1s
&.slide-enter
transform: translate3d(-100%, 0, 0)
&.slide-leave-active
position: absolute
transform: translate3d(-100%, 0, 0)
&:last-child
margin-bottom: 0
.del-btn
flex: 0 0 60px
border: none
outline: none
color: #fff
background: red
transition: all .4s
&.move-enter, &.move-leave-active
transform: translate3d(70px, 0, 0)
.text
flex: 1
padding-left: 20px

如果改变定位过渡的duration与进入离开一样的话,其实可以不用-move,这里设置-move的过渡的duration不同于元素进入离开的duration产生一种速度差,看起来舒服点。而且-leave-active需要设置position: absolute才会有效果。现在看来其实列表过渡也是很容易实现的。

ps:下面看下vue.js 2.* 使用transition实现动画效果