Home > Web Front-end > JS Tutorial > Implement drag-and-drop function based on Vue

Implement drag-and-drop function based on Vue

不言
Release: 2018-05-07 14:49:11
Original
1509 people have browsed it

This article mainly introduces the drag and drop function of Vue in detail. Dragging the block to move has a certain reference value. Interested friends can refer to it.

The examples in this article are shared with you. The specific code for Vue to implement the drag and drop function is provided for your reference. The specific content is as follows

Rendering:

HTML code:

<p id="box">                           
  位置
  <br>x:{{val.x}} <br>y:{{val.y}}
  <p v-drag="greet" id="drag" :style="style">
  //注意这里要通过指令绑定函数将当前元素的位置数据传出来
  </p>
</p>
Copy after login

JS code:

Vue.directive(&#39;drag&#39;,//自定义指令                   

    {bind:function (el, binding) {
        let op = el;  //当前元素
        let self = this; //上下文
        op.onmousedown = function (e) {
         //鼠标按下,计算当前元素距离可视区的距离
          let disX = e.clientX - op.offsetLeft;
          let disY = e.clientY - op.offsetTop;

          document.onmousemove = function (e) {
           //通过事件委托,计算移动的距离 
            let l = e.clientX - disX;
            let t = e.clientY - disY;
           //移动当前元素 
            op.style.left = l + &#39;px&#39;;
            op.style.top = t + &#39;px&#39;;
             //将此时的位置传出去
            binding.value({x:e.pageX,y:e.pageY})
          };
          document.onmouseup = function (e) {
          
            document.onmousemove = null;
            document.onmouseup = null;
           };
        };
      }
    }
  );
  window.onload = function () {
    let vm = new Vue({
      el: &#39;#box&#39;,
      data: {
        val: &#39;123&#39;,
        style: {
          width: &#39;100px&#39;,
          height: &#39;100px&#39;,
          background: &#39;aqua&#39;,
          position: &#39;absolute&#39;,
          right: &#39;30px&#39;,
          top: 0
        }
      },
      methods:{
      //接受传来的位置数据,并将数据绑定给data下的val
        greet(val){
          vm.val = val;
        }
      } ,
   });
  }
Copy after login

Related recommendations:

vue-simplemde Implement image drag and paste function (with code)

Chat example based on vue.js and webpack

The above is the detailed content of Implement drag-and-drop function based on Vue. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template