今天做冒煙測試的時候發現商品發布有一個拖拽圖片排序功能沒做,趕緊加上
之前別的同事基於 vuedraggable 實現過這個功能,我這里自己深度封裝了 el-upload ,用這種方式改動很大,而且感覺不夠優雅。
突然想起之前看的d2-admin項目里面有類似的功能,里面用到了 sortablejs 參考一下。審查元素看看,emmm,可以用。
下載依賴 npm install sortablejs
關鍵代碼如下,輕松實現拖拽排序功能,並且很優雅。
1 <template> 2 <!-- 省略其他配置 --> 3 <el-upload ref="upload" :file-list.sync="fileList"></el-upload> 4 </template> 5 <script> 6 import Sortable from 'sortablejs'; 7 export default { 8 data() { 9 return { 10 fileList: [] 11 }; 12 }, 13 mounted() { 14 this.initDragSort(); 15 }, 16 methods: { 17 initDragSort() { 18 // 支持拖拽排序 19 const el = this.$refs.upload.$el.querySelectorAll('.el-upload-list')[0]; 20 Sortable.create(el, { 21 onEnd: ({ oldIndex, newIndex }) => { 22 // 交換位置 23 const arr = this.fileList; 24 const page = arr[oldIndex]; 25 arr.splice(oldIndex, 1); 26 arr.splice(newIndex, 0, page); 27 } 28 }); 29 } 30 } 31 }; 32 </script>