一、核心實(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)式