Technology Sharing

【vue】Use vue to achieve drag/drop effect

2024-07-12

한어Русский языкEnglishFrançaisIndonesianSanskrit日本語DeutschPortuguêsΕλληνικάespañolItalianoSuomalainenLatina

This week I took on a small outsourcing project, which required me to use Vue to achieve the drag effect shown in the following figure

insert image description here

principle

@mousedownListen for mouse clicks and turn on after clickingmousemove + mouseupListener, and according toclientY + offsetTopCalculate the new top height of the element and assign a value to achieve element following. The specific source code is as follows

<div title="demo" class="icon" @mousedown="demo">
	<img src="../assets/logo.png" alt="">
	<div class="icon_title" :style="{display: state.isShow ? 'block' : 'none'}">
		拖拽下拉新增书签 <br /> 拖回顶部删除书签
	</div>
</div>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
demo(e) {
	//去除默认样式 - 避免拖动元素出现禁止图标
	e.preventDefault && e.preventDefault();
	//获取目标元素
	let odiv = e.target;
	//算出鼠标相对元素的位置
	let disY = e.clientY - odiv.offsetTop;
	let item = {
		top: 0,
		id: 1,
		url: '/src/assets/logo.png'
	}
	//监听鼠标移动事件
	document.onmousemove = (e) => { 
		//用鼠标的位置减去鼠标相对元素的位置,得到元素的位置
		let top = e.clientY - disY;
		//重新赋值
		item.top = top;
	};
	//监听鼠标松开
	document.onmouseup = (e) => {
		document.onmousemove = null;
		document.onmouseup = null;
		//赋值
		this.itemLeft.push(item)

	};
},
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28

Reference Links:Another Vue drag learning reference link: Specific calculation of clientY and other parameters

difficulty

  • When the mouse is pressed and moved, the element drag event will be entered and the mouse prohibition icon will appear. This will interruptmousemoveThe monitoring effect. After searching for a long time, everyone said that writing a dragglable="true" attribute in HTML would be enough, but it didn't work. Finally, I implemented it in one line of code in js.
//去除默认样式 - 避免拖动元素出现禁止图标
e.preventDefault && e.preventDefault();
  • 1
  • 2
  • When pressed, the element should follow the mouse, which requires calculating the relative position of the mouse when pressed. This relative position also needs to be calculated when re-assigning when moving. This is not an easy thing to understand, and it took me a long time to figure it out. I learned it by reading the reference link above.

This article only implements the drag and drop function and records it. I hope that I can achieve perfection when facing similar needs in the future.