本篇文章為大家展示了如何實現(xiàn)vue模塊拖拽效果,代碼簡明扼要并且容易理解,絕對能使你眼前一亮,通過這篇文章的詳細(xì)介紹希望你能有所收獲。

正巧在之前面試中遇到問實現(xiàn)拖拽效果
當(dāng)時面試的時候簡單回答了實現(xiàn)的方式與邏輯。
現(xiàn)在閑來無事,把這個東西實現(xiàn)了一下。
原理很簡單,寫的很方便。
數(shù)據(jù)驅(qū)動,建立一個數(shù)組,數(shù)組初始長度為1
拖動觸發(fā)時,添加一個對象到數(shù)組中,拖動的是下標(biāo)為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; //獲取目標(biāo)元素
//算出鼠標(biāo)相對元素的位置
let disX = e.clientX - odiv.offsetLeft;
let disY = e.clientY - odiv.offsetTop;
let flag = true;
document.onmousemove = (e)=>{ //鼠標(biāo)按下并移動的事件
if(flag && x === this.i.length-1){
flag = false;
this.i.push({input:''})
}
//用鼠標(biāo)的位置減去鼠標(biāo)相對元素的位置,得到元素的位置
let left = e.clientX - disX;
let top = e.clientY - disY;
//綁定元素位置到positionX和positionY上面
this.positionX = top;
this.positionY = left;
//移動當(dāng)前元素
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,后續(xù)用的話可以再豐富,比如以拖動長度來觸發(fā)事件。
input可以換成子組件。這里提供分享一個底層的實現(xiàn)方式
input可以換成子組件。這里提供分享一個底層的實現(xiàn)方式
上述內(nèi)容就是如何實現(xiàn)vue模塊拖拽效果,你們學(xué)到知識或技能了嗎?如果還想學(xué)到更多技能或者豐富自己的知識儲備,歡迎關(guān)注創(chuàng)新互聯(lián)網(wǎng)站制作公司行業(yè)資訊頻道。
名稱欄目:如何實現(xiàn)vue模塊拖拽效果-創(chuàng)新互聯(lián)
網(wǎng)站路徑:http://www.chinadenli.net/article4/pcjoe.html
成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供企業(yè)建站、做網(wǎng)站、Google、自適應(yīng)網(wǎng)站、網(wǎng)站維護(hù)、網(wǎng)站改版
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時需注明來源: 創(chuàng)新互聯(lián)
猜你還喜歡下面的內(nèi)容