Implementation of drag effect of vue module

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

    <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">

    export default {
        name: "index",
            let odiv =;        //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;
              //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
     = left + 'px';
     = top + 'px';
            document.onmouseup = (e) => {
              document.onmousemove = null;
              document.onmouseup = null;

<style scoped lang="less">
    position: absolute;
    top: 0;
    bottom: 0;
    left: 0;
    right: 0;
    background: #f8f8f8;
      width: 250px;
      height: 50px;
      top: 50px;
      left: 10px;
      position: absolute;
      background: red;
      color: yellow;

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

Keywords: Javascript less

Added by emrys404 on Wed, 04 Dec 2019 00:23:17 +0200