Vue,动画-列表动画(添加,删除,进场效果)
时间: 2024-02-24 14:58:40 浏览: 26
Vue中使用动画可以通过Vue的过渡系统来实现,其中包括了三种状态:进入、离开和保持。在列表元素中,添加、删除、进场效果可以通过以下几种方式实现:
1. 添加动画:可以通过在元素外层包裹一个<transition>标签,并设置name属性来实现。在添加元素时,只需将其插入到列表中即可,Vue会自动添加进场动画。例如:
```
<template>
<ul>
<transition name="fade">
<li v-for="item in list" :key="item.id">{{ item.content }}</li>
</transition>
</ul>
</template>
<script>
export default {
data() {
return {
list: []
}
},
methods: {
addItem() {
this.list.push({ id: Date.now(), content: 'new item' })
}
}
}
</script>
<style>
.fade-enter-active,
.fade-leave-active {
transition: opacity 0.5s;
}
.fade-enter,
.fade-leave-to {
opacity: 0;
}
</style>
```
2. 删除动画:同样可以利用<transition>标签来实现。当删除元素时,只需在元素上添加一个类名,Vue会自动添加离场动画。例如:
```
<template>
<ul>
<transition name="fade">
<li v-for="item in list" :key="item.id" :class="{ removed: item.removed }">{{ item.content }}</li>
</transition>
</ul>
</template>
<script>
export default {
data() {
return {
list: [
{ id: 1, content: 'item 1', removed: false },
{ id: 2, content: 'item 2', removed: false },
{ id: 3, content: 'item 3', removed: false }
]
}
},
methods: {
removeItem(index) {
this.list[index].removed = true
setTimeout(() => {
this.list.splice(index, 1)
}, 500)
}
}
}
</script>
<style>
.fade-enter-active,
.fade-leave-active {
transition: opacity 0.5s;
}
.fade-enter,
.fade-leave-to {
opacity: 0;
}
.removed {
position: absolute;
}
</style>
```
3. 进场效果:进场动画与添加动画类似,只需在元素外层包裹<transition>标签,并设置name属性即可。例如:
```
<template>
<ul>
<transition-group name="list">
<li v-for="item in list" :key="item.id">{{ item.content }}</li>
</transition-group>
</ul>
</template>
<script>
export default {
data() {
return {
list: [
{ id: 1, content: 'item 1' },
{ id: 2, content: 'item 2' },
{ id: 3, content: 'item 3' }
]
}
},
methods: {
shuffleList() {
this.list.sort(() => Math.random() - 0.5)
}
}
}
</script>
<style>
.list-enter-active {
transition: all 1s ease-out;
}
.list-enter {
opacity: 0;
transform: translateY(-100%);
}
.list-leave-active {
transition: all 1s ease-out;
}
.list-leave-to {
opacity: 0;
transform: translateY(100%);
}
</style>
```
以上是一些简单的示例,具体的实现方式可以根据需求进行调整。