Vue - 过渡 列表过渡

列表的进入/离开过渡

获取不大于数组长度的随机数,作为插入新值的位置

<div id="app" class="demo">
	<button @click="add">Add</button>
	<button @click="remove">Remove</button>
	<br>
	<br>
	<transition-group name="list">
		<span v-for="item in items" :key="item" class="list-item">{{item}}</span>
	</transition-group>
</div>
<script>
new Vue({
	el: '#app',
	data: {
		items: [1, 2, 3, 4, 5, 6, 7, 8, 9],
		num: 10
	},
	methods: {
		randomIndex () {
			// 获取不超过数组长度的随机数
			return Math.floor(Math.random() * this.items.length)
		},
		add () {
			// 把获取的随机数作为位置插入新元素
			this.items.splice(this.randomIndex(), 0, this.num++)
		},
		remove () {
			// 随机删除某个位置的元素
			this.items.splice(this.randomIndex(), 1)
		}
	}
})
</script>
<style>
.list-item{
	margin-right: 10px;
	display: inline-block;
}
.list-enter-active, .list-leave-active{
	transition: all 1s;
}
.list-enter, .list-leave-to{
	opacity: 0;
	transform: translateY(30px);
}
</style>



列表的排序过渡

<transition-group> 组件还有一个特殊之处。不仅可以进入和离开动画,还可以改变定位。要使用这个新功能只需了解新增的 v-move 特性,它会在元素的改变定位的过程中应用。像之前的类名一样,可以通过 name 属性来自定义前缀,也可以通过 move-class 属性手动设置。

<div id="app">
	<button @click="shuffle">Shuffle</button>
	<br>
	<br>
	<transition-group name="flip-list">
		<li v-for="item in items" :key="item">{{item}}</li>
	</transition-group>
</div>
<script>
new Vue({
	el: '#app',
	data: {
		items: [1, 2, 3, 4, 5, 6, 7, 8, 9]
	},
	methods: {
		shuffle () {
			this.items = _.shuffle(this.items);
		}
	}
})
</script>
<style>
.flip-list-move{
	transition: all .3s;
}
</style>




这个看起来很神奇,内部的实现,Vue 使用了一个叫 FLIP 简单的动画队列
使用 transforms 将元素从之前的位置平滑过渡新的位置。

我们将之前实现的例子和这个技术结合,使我们列表的一切变动都会有动画过渡。

<div id="app">
	<button @click="shuffle">Shuffle</button>
	<button @click="add">Add</button>
	<button @click="remove">Remove</button>
	<br>
	<br>
	<transition-group name="list">
		<span v-for="item in items" :key="item" class="list-item">{{item}}</span>
	</transition-group>
</div>
<script>
new Vue({
	el: '#app',
	data: {
		items: [1, 2, 3, 4, 5, 6, 7, 8, 9],
		num: 10
	},
	methods: {
		randomIndex () {
			// 获取不超过数组长度的随机数
			return Math.floor(Math.random() * this.items.length)
		},
		add () {
			// 把获取的随机数作为位置插入新元素
			this.items.splice(this.randomIndex(), 0, this.num++)
		},
		remove () {
			// 随机删除某个位置的元素
			this.items.splice(this.randomIndex(), 1)
		},
		shuffle () {
			this.items = _.shuffle(this.items)
		}
	}
})
</script>
<style>
.list-item{
	transition: all 1s;
	margin-right: 10px;
	display: inline-block;
}
.list-enter, .list-leave-to{
	opacity: 0;
	transform: translateY(30px);
}
.list-leave-active{
	position: absolute;
}
</style>


>FLIP 动画不仅可以实现单列过渡,多维网格也同样可以过渡: ```


{{cell.number}}
```


posted @ 2018-06-14 07:17  不如吃茶去v  阅读(175)  评论(0编辑  收藏  举报