內部的實現,Vue 使用了一個叫 FLIP 簡單的動畫隊列
使用 transforms 將元素從之前的位置平滑過渡新的位置
需要注意的是使用 FLIP 過渡的元素不能設置為 display: inline 。作為替代方案,可以設置為 display: inline-block 或者放置於 flex 中
FLIP 動畫不僅可以實現單列過渡,多維網格也同樣可以過渡:
<template> <div class="n-tag"> <h1>所有標簽</h1> <button @click="shuffle">shuffle</button> <transition-group name="cell" tag="div" class="container"> <div v-for="cell in cells" :key="cell.id" class="cell"> {{cell.number}} </div> </transition-group> </div> </template> <script> // 要引入lodash.js import _ from "lodash/lodash"; export default { data() { return { cells: Array.apply(null, { length: 81 }).map(function(_, index) { return { id: index, number: index % 9 + 1 }; }) }; }, methods: { shuffle() { this.cells = _.shuffle(this.cells); } } }; </script> <style scoped> .n-tag { background: #fff; padding: 20px; } .container { display: flex; flex-wrap: wrap; width: 238px; margin-top: 10px; } .cell { display: flex; justify-content: space-around; align-items: center; width: 25px; height: 25px; border: 1px solid #aaa; margin-right: -1px; margin-bottom: -1px; } .cell:nth-child(3n) { margin-right: 0; } .cell:nth-child(27n) { margin-bottom: 0; } .cell-move { transition: transform 1s; } </style>
若沒有引入lodash.js 會報錯
修改.eslint.js 文件 ,增加屬性
"globals": {
"document": true,
"localStorage": true,
"window": true,
"_": true
}
然后引用lodash.js
import _ from "lodash/lodash";