Created
November 13, 2015 04:39
-
-
Save JoshZA/acbaa2b2cb303ca4f04a to your computer and use it in GitHub Desktop.
Vue 1x DnD
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!DOCTYPE html> | |
<html lang="en"> | |
<head> | |
<meta charset="UTF-8"> | |
<title>Title</title> | |
<script src="http://rawgit.com/vuejs/vue/1.0.7/dist/vue.js" type="application/javascript"></script> | |
</head> | |
<body> | |
<div id="some-list" class="q" droppable="true" | |
@drop="drop" | |
@dragover.prevent | |
> | |
<div v-for="item in items" draggable="true" track-by="$index" | |
:idx="$index" | |
@dragover.prevent | |
@dragstart="dragstart($event, $index, item)" | |
@dragenter.prevent="dragenter" | |
@dragend.prevent="dragend" | |
> | |
{{item.text}} | |
</div> | |
<pre>{{items | json}}</pre> | |
<pre>{{insertIndex | json}}</pre> | |
<pre>{{srcIdx | json}}</pre> | |
</div> | |
<div id="placeholder"></div> | |
</body> | |
<script type="application/javascript"> | |
(function () { | |
new Vue({ | |
el: '#some-list', | |
data: { | |
items: [ | |
1, | |
2, | |
3, | |
4, | |
5 | |
].map(function (it) { | |
return { | |
text: 'Item-' + it | |
}; | |
}), | |
dragVM: null, | |
dragDom: null, | |
insertIndex: null, | |
srcIdx: null, | |
placeholder: document.getElementById('placeholder') | |
}, | |
methods: { | |
dragstart: function (ev, idx, item) { | |
this.srcIdx = idx; | |
this.dragVM = item; | |
this.dragDom = ev.target; | |
var self = this; | |
Vue.nextTick(function () { | |
self.dragDom.style.opacity = 0.5; | |
}); | |
}, | |
dragend: function (ev) { | |
this.$el.removeChild(this.placeholder); | |
}, | |
drop: function (ev) { | |
this.dragDom.style.opacity = 1; | |
if (this.srcIdx === this.insertIndex) { | |
return; | |
} | |
this.items.$remove(this.dragVM) | |
this.items.splice(this.insertIndex, 0, this.dragVM); | |
}, | |
dragenter: function (ev) { | |
var posElem; | |
this.insertIndex = ev.target.getAttribute('idx'); | |
posElem = this.srcIdx < this.insertIndex ? ev.target : ev.target.previousSibling; | |
this.$el.insertBefore(this.placeholder, posElem.nextSibling); | |
} | |
}, | |
}); | |
}.call(this)); | |
</script> | |
<style type="text/css"> | |
body { | |
background-color: #eee; | |
} | |
.q div { | |
width: 200px; | |
height: 50px; | |
border: solid 1px #ccc; | |
box-shadow: 0 1px 2px 0px #888; | |
background-color: #f8f8f8; | |
margin: 5px; | |
display: block; | |
transition: top 400ms; | |
} | |
.q div#placeholder { | |
opacity: 0.2; | |
} | |
</style> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment