本篇文章為大家展示了如何實現vue模塊拖拽效果,代碼簡明扼要并且容易理解,絕對能使你眼前一亮,通過這篇文章的詳細介紹希望你能有所收獲。
正巧在之前面試中遇到問實現拖拽效果
當時面試的時候簡單回答了實現的方式與邏輯。
現在閑來無事,把這個東西實現了一下。
原理很簡單,寫的很方便。
數據驅動,建立一個數組,數組初始長度為1
拖動觸發時,添加一個對象到數組中,拖動的是下標為0的對象,新建的還在原來位置放著,等待下次拖動。
話不多說,上代碼
<template>
<div>
<div @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>
.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可以換成子組件。這里提供分享一個底層的實現方式
input可以換成子組件。這里提供分享一個底層的實現方式
上述內容就是如何實現vue模塊拖拽效果,你們學到知識或技能了嗎?如果還想學到更多技能或者豐富自己的知識儲備,歡迎關注億速云行業資訊頻道。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。