原文地址【vue中原生H5拖拽排序_拖拽图片也是同样的道理】
H5有基于拖拽的事件机制,如果你还不熟悉,请看我之前的文章【拖拽上传】中有介绍。
原生拖拽API实现
由于比较简单直接上代码了:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>拖拽排序</title>
<script src="https://cdn.bootcdn.net/ajax/libs/vue/2.7.9/vue.min.js"></script>
<style>
ul {
clear: both;
list-style: none;
overflow: hidden;
}
li {
cursor: pointer;
float: left;
height: 32px;
line-height: 30px;
padding: 0 10px;
color: #409eff;
border: 1px solid #d9ecff;
background-color: #ecf5ff;
}
</style>
</head>
<body>
<div id="app"></div>
<script>
new Vue({
template: `
<div>
<h1 style="padding-left: 30px;">连词成句</h1>
<ul>
<li v-for="(item,index) in list" :key="index" draggable="true" @dragstart="dragstart(item)"
@dragenter="onDragEnter(item,$event)" @dragend="onDragEnd">{{item}}</li>
</ul>
</div>
`,
el: '#app',
data() {
return {
oldWord: null,
newWord: null,
list: ["校长", "爷爷", "我", "给", "唱了首歌"]
}
},
methods: {
dragstart(word) {
this.oldWord = word
},
// 记录移动过程中信息
onDragEnter(word, e) {
this.newWord = word
e.preventDefault()
},
// 拖拽结束
onDragEnd() {
if (this.oldWord !== this.newWord) {
let oldWordIndex = this.list.indexOf(this.oldWord);
let newWordIndex = this.list.indexOf(this.newWord);
let newList = [...this.list];
// 删除老的节点
newList.splice(oldWordIndex, 1);
// 在列表中目标位置增加新的节点
newList.splice(newWordIndex, 0, this.oldWord);
this.list = [...newList];
}
}
}
})
</script>
</body>
</html>
效果如下:
使用vuedraggable
实现拖拽排序
vuedraggable 是基于sortable.js实现的,所以需要先引入sortable.js,如果是npm安装的,则无需再引入。
使用起来也比较简单,代码如下
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>拖拽排序</title>
<script src="https://cdn.bootcdn.net/ajax/libs/vue/2.7.9/vue.min.js"></script>
<script src="//cdn.jsdelivr.net/npm/sortablejs@1.8.4/Sortable.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/Vue.Draggable/2.20.0/vuedraggable.umd.min.js"></script>
<style>
ul {
clear: both;
list-style: none;
overflow: hidden;
}
li {
cursor: pointer;
float: left;
height: 32px;
line-height: 30px;
padding: 0 10px;
color: #409eff;
border: 1px solid #d9ecff;
background-color: #ecf5ff;
}
</style>
</head>
<body>
<div id="app"></div>
<script>
let draggable = vuedraggable;
new Vue({
components: {draggable},
template: `
<div>
<h1 style="padding-left: 30px;">连词成句</h1>
<ul>
<draggable v-model="list" group="people" @start="drag=true" @end="drag=false">
<li v-for="(item,index) in list" :key="index">{{item}}</li>
</draggable>
</ul>
</div>
`,
el: '#app',
data() {
return {
drag: false,
list: ["校长", "爷爷", "我", "给", "唱了首歌"]
}
}
})
</script>
</body>
</html>
参考资料
- 拖拽上传
- vue中使用vuedraggable实现图片的拖拽排序
- 基于vue element-ui 封装上传图片组件 功能:上传,删除,预览,上传图片水印,拖拽排序,上传进度条等