基于Vue实现拖拽效果之数组拖拽排序
拖拽的核心是:dragstart, dragenter,dragend的方法动画采用 transition-group 的方法<!DOCTYPE html><html lang="en"><head><meta http-equiv="Content-Type" content="text/html; charset=utf-8" /><met
·
拖拽的核心是:dragstart, dragenter, dragend 的方法
动画采用 transition-group 的方法
<!DOCTYPE html>
<html lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name="viewport" content="initial-scale=1, maximum-scale=1, minimum-scale=1, user-scalable=no, width=device-width" />
<title>test</title>
<style type="text/css">
.flip-list-move {
transition: transform 0.3s ease-in;
}
.box {
display: block;
display: flex;
width: 500px;
flex-wrap: wrap;
}
.items {
width: 100px;
height: 50px;
margin: 10px;
line-height: 50px;
text-align: center;
border: 1px solid red;
cursor: move;
}
.items.active {
background: rgba(0, 0, 0, 0.4);
}
</style>
</head>
<body>
<div id="content">
<transition-group name="flip-list" class="box">
<div v-for="item in items" :key="item" draggable="true" class="items" :class="{active: oldVal == item && isActive==item}" @dragstart="dragstart(item)" @dragenter="dragenter(item)" @dragend="dragend(item)">
{{item}}
</div>
</transition-group>
</div>
<script src="https://cdn.bootcdn.net/ajax/libs/vue/2.6.9/vue.min.js"></script>
<script>
var vue = new Vue({
el: '#content',
data: {
items: [1, 2, 3, 4, 5, 6, 7, 8, 9],
isActive: 0,
oldVal: 0,
newOld: 0,
},
methods: {
dragstart(val) {
this.oldVal = val;
this.isActive = val;
},
dragend(val) {
if (this.oldVal != this.newOld) {
let oldIndex = this.items.indexOf(this.oldVal);
let newIndex = this.items.indexOf(this.newOld);
let newItems = [...this.items];
// 删除老的节点
newItems.splice(oldIndex, 1);
// 增加新的节点
newItems.splice(newIndex, 0, this.oldVal);
// items结构发生变化触发transition-group的动画
this.items = [...newItems];
this.isActive = -1;
}
},
// 记录移动过程中信息
dragenter(val) {
this.newOld = val;
},
},
});
</script>
</body>
</html>```
更多推荐
已为社区贡献33条内容
所有评论(0)