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

正巧在之前面試中遇到問(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)單,寫(xiě)的很方便。
數(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>
<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)相對(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>
.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)方式
input可以換成子組件。這里提供分享一個(gè)底層的實(shí)現(xiàn)方式
上述內(nèi)容就是如何實(shí)現(xiàn)vue模塊拖拽效果,你們學(xué)到知識(shí)或技能了嗎?如果還想學(xué)到更多技能或者豐富自己的知識(shí)儲(chǔ)備,歡迎關(guān)注創(chuàng)新互聯(lián)網(wǎng)站制作公司行業(yè)資訊頻道。
名稱欄目:如何實(shí)現(xiàn)vue模塊拖拽效果-創(chuàng)新互聯(lián)
網(wǎng)站路徑:http://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)請(qǐng)盡快告知,我們將會(huì)在第一時(shí)間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如需處理請(qǐng)聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時(shí)需注明來(lái)源: 創(chuàng)新互聯(lián)
猜你還喜歡下面的內(nèi)容