<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Document</title> <script src="./vue-2.5.16.js"></script> <style> ul { padding: 0; margin: 0; list-style: none; } li { border: 1px dashed #ccc; background-color: #eee; line-height: 35px; font-size: 12px; padding-left: 10px; margin: 10px 0; } .v-enter, .v-leave-to { opacity: 0; transform: translateY(300px); } .v-enter-active, .v-leave-active { transition: all 2s ease; } /* 控制 即将被删除的那个元素,脱离标准流,从而允许后续的元素,往上顶 */ .v-leave-active { position: absolute; width: 100%; } /* vue自带的效果 控制 那些将要往上顶的元素,通过 过渡,渐渐地顶上来 */ .v-move { transition: all 2s ease; } </style> </head> <body> <div id="app"> <div> <input type="text" v-model="name"> <button @click="add">添加</button> </div> <ul> <!-- 1. 如果要为列表添加动画,必须使用 transition-group 把 v-for 循环渲染的元素,包裹起来 --> <transition-group> <li v-for="item in arr" :key="item.id" @click="remove(item.id)"> {{item.name}} </li> </transition-group> </ul> </div> <script> // 创建 Vue 实例,得到 ViewModel var vm = new Vue({ el: '#app', data: { // 新添加的用户名称 name: '', arr: [ { id: 1, name: '张三' }, { id: 2, name: '李四' }, { id: 3, name: '赵六' } ] }, methods: { add() { const user = { id: this.arr.length + 1, name: this.name } this.arr.push(user) this.name = '' }, remove(id) { const i = this.arr.findIndex(x => x.id === id) this.arr.splice(i, 1) } } }); </script> </body> </html>