sortable 對(duì)for動(dòng)態(tài)列表拖拽排序,vue獲取排序后的數(shù)據(jù)

一、核心實(shí)現(xiàn)代碼

<template>
  <div>
    <!-- 動(dòng)態(tài)列表容器 -->
    <ul ref="sortableList">
      <li 
        v-for="(item, index) in list" 
        :key="item.id"  <!-- id值必須唯一,動(dòng)態(tài)新增的id值注意唯一性 -->
        class="sortable-item"
      >
        {{ index + 1 }}. {{ item.name }}
      </li>
    </ul>
    
    <!-- 顯示排序結(jié)果 -->
    <div>當(dāng)前順序:{{ sortedIds }}</div>
  </div>
</template>

<script>
import Sortable from 'sortablejs';

export default {
  data() {
    return {
      // 初始數(shù)據(jù)(可替換為接口獲?。?      list: [
        { id: 1, name: '蘋果' },
        { id: 2, name: '香蕉' },
        { id: 3, name: '橘子' }
      ]
    };
  },
  computed: {
    // 實(shí)時(shí)獲取排序后的ID序列
    sortedIds() {
      return this.list.map(item => item.id).join(', ');
    }
  },
  mounted() {
    this.initSortable();
  },
  methods: {
    initSortable() {
      const el = this.$refs.sortableList;
      
      Sortable.create(el, {
        animation: 150,
        ghostClass: 'sortable-ghost',
        onEnd: (evt) => {
          // 處理數(shù)據(jù)順序變化
          this.handleSort(evt.oldIndex, evt.newIndex);
        }
      });
    },
    handleSort(oldIndex, newIndex) {
      // 使用Vue的數(shù)組方法保持響應(yīng)式
      const movedItem = this.list.splice(oldIndex, 1)[0];
      this.list.splice(newIndex, 0, movedItem);

      //此時(shí)this.list列表,已是拖拽后的排序順序,可直接提交后端,按此排序
      console.log('排序后的列表', this.list);
      
      // 提交最新數(shù)據(jù)
      this.submitOrder();
    },
    submitOrder() {
      // 發(fā)送到后端(示例)
      const payload = {
        sortedIds: this.sortedIds,
        fullData: this.list
      };
      console.log('提交數(shù)據(jù):', payload);
      
      // 實(shí)際調(diào)用API示例
      // this.$http.post('/api/update-order', payload);
    }
  }
};
</script>

<style>
.sortable-item {
  padding: 10px;
  margin: 5px;
  border: 1px solid #ddd;
  cursor: move;
  transition: all 0.3s;
}

.sortable-ghost {
  opacity: 0.6;
  background: #f0f9ff;
}
</style>

二、關(guān)鍵實(shí)現(xiàn)原理

1.動(dòng)態(tài)列表綁定

  • 通過 v-for 渲染動(dòng)態(tài)數(shù)據(jù)
  • :key 必須使用唯一標(biāo)識(shí)(如 item.id)

2.Sortable 初始化

  • 在 mounted 生命周期初始化
  • 綁定到 ref 引用的容器元素

2.數(shù)據(jù)同步機(jī)制

  • 在 onEnd 事件中通過 splice 操作數(shù)組
  • 使用 Vue 的數(shù)組變異方法保持響應(yīng)式
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容