溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

vue模塊拖拽實(shí)現(xiàn)示例代碼

發(fā)布時(shí)間:2020-08-22 12:54:02 來(lái)源:腳本之家 閱讀:149 作者:王_ye 欄目:web開發(fā)

正巧在之前面試中遇到問(wèn)實(shí)現(xiàn)拖拽效果

當(dāng)時(shí)面試的時(shí)候簡(jiǎn)單回答了實(shí)現(xiàn)的方式與邏輯。

現(xiàn)在閑來(lái)無(wú)事,把這個(gè)東西實(shí)現(xiàn)了一下。

原理很簡(jiǎn)單,寫的很方便。

數(shù)據(jù)驅(qū)動(dòng),建立一個(gè)數(shù)組,數(shù)組初始長(zhǎng)度為1

拖動(dòng)觸發(fā)時(shí),添加一個(gè)對(duì)象到數(shù)組中,拖動(dòng)的是下標(biāo)為0的對(duì)象,新建的還在原來(lái)位置放著,等待下次拖動(dòng)。

話不多說(shuō),上代碼

<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;    //獲取目標(biāo)元素
      //算出鼠標(biāo)相對(duì)元素的位置
      let disX = e.clientX - odiv.offsetLeft;
      let disY = e.clientY - odiv.offsetTop;
      let flag = true;
      document.onmousemove = (e)=>{    //鼠標(biāo)按下并移動(dòng)的事件
       if(flag && x === this.i.length-1){
        flag = false;
        this.i.push({input:''})
       }
       //用鼠標(biāo)的位置減去鼠標(biāo)相對(duì)元素的位置,得到元素的位置
       let left = e.clientX - disX;
       let top = e.clientY - disY;
       //綁定元素位置到positionX和positionY上面
       this.positionX = top;
       this.positionY = left;
       //移動(dòng)當(dāng)前元素
       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>

一個(gè)簡(jiǎn)單的demo,后續(xù)用的話可以再豐富,比如以拖動(dòng)長(zhǎng)度來(lái)觸發(fā)事件。

input可以換成子組件。這里提供分享一個(gè)底層的實(shí)現(xiàn)方式

以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持億速云。

向AI問(wèn)一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI