效果:
拖拽排序
背景:
作為一名前端開發人員,在工作中難免會遇到拖拽功能,分享一個github上一個不錯的拖拽js庫,能滿足我們在項目開發中的需要,下面是我在uniapp中使用SortableJS的使用詳細流程;?
vue開發的web項目可以參考我的另一篇文章
Vue中拖動排序功能,引入SortableJs,前端拖動排序。https://blog.csdn.net/weixin_64530670/article/details/132328122?spm=1001.2014.3001.5501
開始前先下載好Sortable至項目中,可直接下載min包,官方文檔:
SortableJs中文文檔http://www.sortablejs.com
- ??sortable??下載到本地????renderjs??只支持H5和App-vue,不支持小程序和App-nvue開發
- 下載好后,在html代碼處,找到你要拖拽排序的元素的父元素,給它設置一個id,我這邊設置的就是'sort'? ,然后 給要拖拽的元素設置:data-id? ? 它的作用是,決定了拖拽結束后返回給你一個怎樣的數組,傳item.id,它就會自動在拖拽結束后返回給你一個拖拽后排序好的id數組. 然后我們就可以拿去處理數據,發請求保存順序啦!
<view class="appList" id="sort"><view class="appItem" v-for="(item,index) in usualist" :key='item.appId' :data-id="item.appId"><view class="remove" @tap="remove(item)"><u-icon name="minus-circle-fill"></u-icon></view><image class="img" :src='getimgUrl(item.overImgUrl)' v-if="Boolean(item.overImgUrl)"></image><view class="first" v-else>{{getfirst(item.name)}}</view><view class="appIntroduction"><text>{{item.name}}</text></view><view class="totop"><u-icon name="list"></u-icon></view></view></view>
-
css:
.sort {display: flex;align-items: center;flex-wrap: wrap;&-item {width: 200rpx;height: 100rpx;display: flex;align-items: center;justify-content: center;border-radius: 15rpx;background: #f5f5f5;margin: 5rpx;}}
-
js代碼 再寫一個script標簽:
<script module='sortable' lang="renderjs"> import Sortable from 'static/Sortable.min.js' export default {mounted() {this.initSortable()},methods: {initSortable() {if (typeof window.Sortable === 'function') {this.setSortable()} else {const script = document.createElement('script')script.src = '/static/Sortable.min.js'script.onload = this.setSortable.bind(this)document.head.appendChild(script)}},setSortable() {let option = {animation: 150,delay:300,onEnd: (e) => {// 拖拽完成后回調this.$ownerInstance.callMethod('changeSort', sortable.toArray());}}let sortable = Sortable.create(document.getElementById('sort'), option);},} } </script>
以上代碼中,在執行完拖拽后會執行changeSort方法,這個方法需要寫到原本的那個script中:
changeSort(e) {console.log(e)this.flag = truethis.updatelist = e.join(',')},
拖拽后打印出來的e就是有已經排序好的每一項的id組成的數組。