Vue过渡与动画组

Vue过渡与动画组教程

Vue 过渡与动画 在实现列表过渡的时候,如果需要过渡的元素,是通过 v-for 渲染出来的,不能使用 transition 包裹,需要使用 transition-group。

案例

Vue过渡与动画组

<!DOCTYPE html> <html> <head> <title>Vue 过渡及动画组</title> <script type="text/javascript" src="./lib/vue-2.6.10.min.js"></script> </head> <style type="text/css"> li{ border: 1px dashed #999; margin: 5px; line-height: 35px; font-size: 14px; padding-left: 5px; width: 100%; } li:hover{ background-color: hotpink; transition: all 0.5s ease; } .v-enter,.v-leave-to{ opacity: 0; transform: translateY(80px); } .v-enter-active,.v-leave-active{ transition: all 0.6s ease; } /*v-move 和 v-leave-active 配合使用,能够实现列表后续的元素,渐渐地漂上来的效果 */ .v-move{ transition: all 0.6s ease; } .v-leave-active{ position: absolute; } </style> <body> <div id="app"> <div> <label> ID: <input type="text" v-model="id"> </label> <label> Name: <input type="text" v-model="name"> </label> <input type="button" value="Add" @click="add"> </div> <ul> <!--在实现列表过渡时,如果需要过渡的元素是通过v-for渲染出来的,不能使用 transition 包裹,需要使用 transition-group --> <!--若需要为 v-for 循环创建的元素设置动画,必须为每一个元素设置 :key 属性--> <transition-group> <li v-for="(item,i) in list" :key="item.id" @click="del(i)"> {{ item.id }} --- {{ item.name }} </li> </transition-group> </ul> <p>嗨客网(www.haicoder.net)</p> </div> </body> <script type="text/javascript"> var vm = new Vue({ el : '#app', data : { id:'', name :'', list : [ {id:1,name:'Vue'}, {id:2,name:'Golang'}, {id:3,name:'Docker'}, {id:4,name:'Mysql'}, ], }, methods : { add(){ this.list.push({ id :this.id,name : this.name}); this.id = this.name = ''; }, del(i){ this.list.splice(i,1); }, } }); </script> </html>

浏览器运行效果如下图所示:

07 vue transition group.png

我们使用 transition-group 来定义 v-for 包裹元素的动画。

Vue过渡与动画组总结

Vue 过渡与动画在实现列表过渡的时候,如果需要过渡的元素,是通过 v-for 渲染出来的,不能使用 transition 包裹,需要使用 transition-group。