It happens that in the previous interview, we met with questions to achieve drag effect
At the time of interview, I simply answered the way and logic of implementation.
Now I have nothing to do, and I have realized this thing.
The principle is very simple and easy to write.
Data driven, create an array with an initial length of 1
When dragging is triggered, add an object to the array. Drag the object with subscript 0. The new object is still in the original position, waiting for the next drag.
Don't talk much
<template> <div class="view"> <div class="x" @mousedown="move($event,index)" v-for="(x,index) in i"> <span v-if="index+1 !== i.length">{{index+1}}</span> <input v-model="x.input"> </div> {{i}} </div> </template> <script> export default { name: "index", data(){ return{ positionX:0, positionY:0, i:[ {input:''} ] } }, methods:{ move(e,x){ let odiv = e.target; //Get target element //Figure out the position of the mouse relative to the element let disX = e.clientX - odiv.offsetLeft; let disY = e.clientY - odiv.offsetTop; let flag = true; document.onmousemove = (e)=>{ //Mouse down and move events if(flag && x === this.i.length-1){ flag = false; this.i.push({input:''}) } //Subtract the position of the mouse relative to the element from the position of the mouse to get the position of the element let left = e.clientX - disX; let top = e.clientY - disY; //Bind elements to positions X and Y this.positionX = top; this.positionY = left; //Move current element odiv.style.left = left + 'px'; odiv.style.top = top + 'px'; }; document.onmouseup = (e) => { document.onmousemove = null; document.onmouseup = null; }; } } } </script> <style scoped lang="less"> .view{ position: absolute; top: 0; bottom: 0; left: 0; right: 0; background: #f8f8f8; .x{ width: 250px; height: 50px; top: 50px; left: 10px; position: absolute; background: red; color: yellow; } } </style>
A simple demo can be enriched for subsequent use, such as triggering events by dragging length.
input can be replaced with subcomponents. Here is a way to share an underlying implementation