列表的进入/离开过渡,对列表直接操作(增、删)的元素,封装<transition-group>并按常规的CSS或JS过渡即可;但在操作这些元素的位置变化时,由于DOM文档流的变化,会同时引起其它(邻近)节点元素的位置变化,例如在列表插入一个<li>,插入点原本的<li>会下移,删除一个<li>,下面的<li>会上移补充占据这个位置。 对于这些“被动”移动的元素来说,也可以实现过渡,这就用到了v-move
特性。
v-move
特性。会在元素的改变定位的过程中应用。
像之前的类名一样,可以通过 name
属性来自定义前缀:v-move {/*transition*/}。
也可以通过 move-class
属性手动设置: <span move-class='***'>。
官方教程的例子,数字列表随机位置添加和移除数字。
当添加和移除元素的时候,周围的元素会瞬间移动到他们的新布局的位置,而不是平滑的过渡。
使用v-move解决
注释部分为实现效果的思路(keng),结合Vue论坛解答的个人理解。
1. 可以给<transition>组件中的元素设置name,再赋予v-move类,设置CSS transition属性。
2. 也可以给列表的所有元素都添加一个类,直接给这个类设置CSS transition属性,元素移动的时候自动获得v-move。
3. 用splice删除数组的元素,由于删除的元素经理了一个过渡,始终占据文档流的这个位置,因此下一个元素要等待其过渡消失后再移动过来,造成一个生硬的效果。要达到平滑过渡,就要在删除元素leave-active阶段用position:absolute将其移出文档流,后面的元素才能同时平滑过渡过来。
There's a small detail about the move transition, which is that the -leave-active transition class must apply a position: absolute declaration, in order to take it out of the layout flow, so the siblings can -move in to place around it.
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv='Content-Type' content='text/html; charset=uft-8'>
<title>flip-list-demo</title>
<style type='text/css'></style>
<script src = "https://unpkg.com/vue"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.14.1/lodash.min.js"></script>
</head>
<body>
<div id='flip-list-demo' class='flip'>
<button @click='add'>add</button>
<button @click='remove'>remove</button>
<button @click='shuffle'>shuffle</button>
<transition-group name='flip-list' tag='ul' mode='in-out'>
<li v-for='item in items' :key='item' class='flip-list-item'>{{item}}</li>
</transition-group>
</div>
</body>
</html>
var app = new Vue({
el:'#flip-list-demo',
data:{
items:[1,2,3,4,5,6,7,8,9],
nextNum:10
},
methods:{
randomIndex: function () {
return Math.floor(Math.random()*this.items.length);
},
add: function () {
this.items.splice(this.randomIndex(),0,this.nextNum++);
},
remove: function () {
this.items.splice(this.randomIndex(),1);
},
/* shuffle方法只是排序效果,与平滑过渡没关系;平滑过渡是利用v-move */
shuffle: function () {
this.items = _.shuffle(this.items);
}
}
})
.flip-list-item {
list-style-type: none;
/**
* 可以在v-enter-active和v-move中分别用transition过渡,也可以在item中用transition,包含了这两项
* 要用all不用transform,有可能是因为splice删除效果不是transform
*/
/* transition: all 1s; */
}
.flip-list-enter-active,.flip-list-leave-active {
transition: all 1s;
}
.flip-list-move {
transition: all 1s;
}
.flip-list-enter,.flip-list-leave-to {
opacity:0;
transform: translateX(50px);
}
/**
* 要让删除的元素先脱离文档流,旁边的元素才能过渡过来
*/
.flip-list-leave-active {
position:absolute;
}