H5有基于拖拽的事件机制,如果你还不熟悉,请看我之前的文章【拖拽上传】中有介绍。
由于比较简单直接上代码了:
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: `
连词成句
- {{item}}
`,
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: `
连词成句
- {{item}}
`,
el: '#app',
data() {
return {
drag: false,
list: ["校长", "爷爷", "我", "给", "唱了首歌"]
}
}
})
script>
body>
html>
参考资料