1. 程式人生 > >vue模塊拖拽實現示例代碼

vue模塊拖拽實現示例代碼

off lan 現在 簡單 comm etl nbsp xhtml www

正巧在之前面試中遇到問實現拖拽效果

當時面試的時候簡單回答了實現的方式與邏輯。

現在閑來無事,把這個東西實現了一下。

原理很簡單,寫的很方便。

數據驅動,建立一個數組,數組初始長度為1

拖動觸發時,添加一個對象到數組中,拖動的是下標為0的對象,新建的還在原來位置放著,等待下次拖動。

話不多說,上代碼

?
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 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 <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; //獲取目標元素 //算出鼠標相對元素的位置 let disX = e.clientX - odiv.offsetLeft;
let disY = e.clientY - odiv.offsetTop; let flag = true; document.onmousemove = (e)=>{ //鼠標按下並移動的事件 if(flag && x === this.i.length-1){ flag = false; this.i.push({input:‘‘}) } //用鼠標的位置減去鼠標相對元素的位置,得到元素的位置 let left = e.clientX - disX; let top = e.clientY - disY; //綁定元素位置到positionX和positionY上面 this.positionX = top; this.positionY = left; //移動當前元素 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>

一個簡單的demo,後續用的話可以再豐富,比如以拖動長度來觸發事件。

input可以換成子組件。這裏提供分享一個底層的實現方式

vue模塊拖拽實現示例代碼