效果图:
1.首先,我们需要在vue项目中安装依赖:
npm install -save sortablejs
2.创建demo文件=>demoTest.vue,直接附上实例代码:
<template>
<div>
<div id="table-names">
<div class="tableItem" v-for="item of tableData" :key="item.id">
<span>{{ item.id }}</span>
=>
<span>{{ item.name }}</span>
=>
<span>{{ item.sort }}</span>
</div>
</div>
<el-button @click="refreshData">刷新</el-button>
<el-button @click="initData">取缓存</el-button>
</div>
</template>
<script>
import Sortable from 'sortablejs'
let tableDemoSort = 'DEMOSORT'
const list = [
{name: 'laowang1', id: '0', sort: 1},
{name: 'laowang2', id: '1', sort: 2},
{name: 'laowang3', id: '2', sort: 3},
{name: 'laowang4', id: '3', sort: 4}
]
export default {
data(){
return{
tableData:[]
}
},
computed: {},
created() {
this.initData()
},
mounted(){
this.dragTable()
},
methods:{
initData() {
let stData = this.getTableDataToLocalStorage()
console.log('initData=>stData', JSON.stringify(stData))
if (stData) {
this.tableData = JSON.parse(JSON.stringify(stData))
// this.$forceUpdate()
} else {
this.tableData = list
}
this.setTableDataToLocalStorage(this.tableData)
},
refreshData() {
this.tableData = list
this.setTableDataToLocalStorage(this.tableData)
},
setTableDataToLocalStorage(data) {
localStorage.setItem(tableDemoSort, JSON.stringify(data))
},
getTableDataToLocalStorage() {
return JSON.parse(localStorage.getItem(tableDemoSort))
},
dragTable(){
let el = document.getElementById('table-names')
Sortable.create(el, {
animation: 200,
chosenClass: "chosenClass", // 被选中项的css 类名
// dragClass: "dragClass", // 正在被拖拽中的css类名
onEnd: evt => {
let {oldIndex, newIndex} = evt
this.switchMapOrder(oldIndex, newIndex)
}
})
},
switchMapOrder(oldIndex, newIndex){
console.log(`oldIndex: ${oldIndex}, newIndex: ${newIndex}`)
const tableData = this.tableData
let resultData = [] // 结果数组
// 先把被移动的那条数据单独取出来
let beSpliceItem = tableData.splice(oldIndex, 1)
// 把剩下的数据复制给结果数组
resultData = tableData
// 把被移动的那条数据赋值给结果数组
resultData.splice(newIndex, 0, beSpliceItem[0])
// 遍历结果数组,让sort重新排序
let newTableData = []
resultData.forEach((item, index) => {
item.sort = index + 1
newTableData.push(item)
})
this.tableData = newTableData
// this.$forceUpdate()
this.setTableDataToLocalStorage(newTableData)
// this.dragTable()
}
}
}
</script>
<style>
#table-names {
display: flex;
flex-direction: column;
}
.tableItem{
padding: 6px 10px;
cursor: pointer;
}
.sortable-chosen{
background-color: blue;
}
/* // 拖拽 */
.dragClass {
background-color: rgba(0, 188, 235, 0.5) !important;
color: #0000a3 !important;
}
/* // 停靠 */
.ghostClass {
background-color: rgba(0, 191, 243, 0.1) !important;
}
/* // 选择 */
.chosenClass {
background-color: rgba(0, 188, 235, 0.2) !important;
}
</style>
3.提供一个列表拖动排序的文档,想要了解更多,请查看文档:http://www.sortablejs.com/options.html