vue change the position of two elements (same array or list) by dragging and dropping

<!DOCTYPE html>
<html>

<head>
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<meta name="apple-mobile-web-app-title" content="">
<meta name="apple-mobile-web-app-capable" content="yes" />
<meta name="apple-touch-fullscreen" content="yes" />
<meta http-equiv="Cache-Control" content="no-siteapp" />
<meta name="format-detection" content="telephone=no" />
<meta content="email=no" name="format-detection" />
<meta name="msapplication-tap-highlight" content="no">
<meta name="description" content="">
<meta name="keywords" content="">
<meta name="viewport" content="width=device-width, initial-scale=1,user-scalable=no">
<script src="js/jquery-1.12.3.js"></script>
<script src="js/vue.min.js"></script>
<title>H5拖放</title>
<style>
	.square{
		width: 200px;
		height: 50px;
		line-height: 50px;
		margin-bottom: 60px;
		text-align: center;
		background-color: #5BC0DE;
		font-size: 20px;
		color: #fff;
	}
	
	.big_box{
		width: 400px;
		height: 200px;
		background-color: #006600;
	}
</style>
</head>
<body>
<div id="vueBox">	
	<div class="square" v-for="(item,$index) in squareList" 
		@dragstart="dragstart($index,$event)"
		@dragend="dragend($event)" @drop="drop($index,$event)" @dragover="dragover($event)" 
		draggable="true">{{item.index}}</div>
	<div class="big_box" @drop="drop($event)" @dragover="allowDrop($event)"></div>
</div>

<script>
	
	var vm = new Vue({
		el:"#vueBox",
		data:{
			squareList:[],
			moveIndex:null,
			targetIndex:null
		},
		methods:{
			dragstart:function(index){
				var that = this;
				console.log("拖放开始",index);
				that.moveIndex = index;
			},
			dragover:function(event){  //必须添加dragover事件,不然drop事件也无效
				event.preventDefault(); 
			},
			dragend:function(event){
				console.log("拖放结束",event.currentTarget);
			},
			drop:function(index,event){
				var that = this;
				//阻止默认行为
				event.preventDefault();
				//阻止默认行为
				event.stopPropagation();
				console.log("拖放到目标",index);
				that.targetIndex = index;
				
				//先保存拖动元素index
				var temp = that.squareList[that.moveIndex].index;
				//将拖动元素位置index换成目标元素的index
				that.squareList[that.moveIndex].index = that.squareList[that.targetIndex].index;
				//将目标元素位置index换成拖动元素的index
				that.squareList[that.targetIndex].index = temp;
				console.log(JSON.stringify(that.squareList));
			},
			allowDrop:function(event){
				event.preventDefault();  
			},
			getSquareList:function(){
				var that = this;
				for(var i=0;i<4;i++){
					(function(i){
						var obj = {
							index:i,							
						}
						that.squareList.push(obj);
					}(i))
				}
			}
			
		},
		mounted:function(){
			var that = this;
			that.getSquareList();
		}
	});

</script>
</body>
</html>

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325560939&siteId=291194637