Vue使用自定義指令實(shí)現(xiàn)拖拽行為實(shí)例分析
本文實(shí)例講述了Vue使用自定義指令實(shí)現(xiàn)拖拽行為。分享給大家供大家參考,具體如下:
需求通過(guò)自定義指令的方式實(shí)現(xiàn)拖拽效果,預(yù)期的使用方式為:
<div v-drag> XXXX</div>
更重要的一個(gè)需求點(diǎn):
拖拽元素內(nèi)部的子元素可以自行阻止拖拽行為比如:
<div v-drag> <el-button @mousedown.native.stop>test</el-button></div>
曾經(jīng)使用過(guò)vue-resizable,由于該組件是通過(guò)事件捕獲的方式實(shí)現(xiàn)的,拖拽元素的子元素也會(huì)觸發(fā)拖拽行為,不符合開(kāi)發(fā)需求,所以自行實(shí)現(xiàn)了拖拽指令,相關(guān)源碼如下。
無(wú)任何依賴,復(fù)制即可使用
源碼/** * @file 自定義拖拽命令 */import Vue from ’vue’;const Drag = { install(Vue: any) { // 如需禁止拖拽元素內(nèi)部某些元素觸發(fā)拖拽,在內(nèi)部不可觸發(fā)拖拽元素上添加@mousedown.native.stop即可 Vue.directive(’drag’, { bind(el: any) {el.style.position = ’absolute’;el.style.zIndex = el.style.zIndex || ’3000’; }, inserted(el: any) {// 設(shè)置元素初始位置const boundingClientRect = el.getBoundingClientRect();el.style.left = boundingClientRect.x + ’px’;el.style.top = boundingClientRect.y + ’px’;// 將拖拽元素置于body子元素,防止被relative的父元素遮擋document.body.appendChild(el);let originX: number;let originY: number;const mouseDownHandler = (evt: MouseEvent) => { originX = evt.clientX - el.offsetLeft; originY = evt.clientY - el.offsetTop; el.style.cursor = ’pointer’;};const mouseMoveHandler = (evt: MouseEvent) => { if (evt.buttons === 1 && originX && originY) { el.style.left = evt.clientX - originX + ’px’; el.style.top = evt.clientY - originY + ’px’; }};const mouseUpHandler = () => { el.style.cursor = ’default’;};el.addEventListener(’mousedown’, mouseDownHandler);el.addEventListener(’mousemove’, mouseMoveHandler);el.addEventListener(’mouseup’, mouseUpHandler);el.__mouseDownHandler__ = mouseDownHandler;el.__mouseMoveHandler__ = mouseMoveHandler;el.__mouseUpHandler__ = mouseUpHandler; }, unbind(el: any) {el.removeEventListener(’mousedown’, el.__mouseDownHandler__);el.removeEventListener(’mousemove’, el.__mouseMoveHandler__);el.removeEventListener(’mouseup’, el.__mouseUpHandler__);// 當(dāng)父組件銷毀觸發(fā)unbind的時(shí)候需要手動(dòng)刪除這個(gè)節(jié)點(diǎn),不然會(huì)一直存留在body中el.parentNode.removeChild(el); } }); }};Vue.use(Drag);export default Drag;
希望本文所述對(duì)大家vue.js程序設(shè)計(jì)有所幫助。
相關(guān)文章:
1. 基于PHP做個(gè)圖片防盜鏈2. ASP.NET MVC使用Boostrap實(shí)現(xiàn)產(chǎn)品展示、查詢、排序、分頁(yè)3. XML在語(yǔ)音合成中的應(yīng)用4. asp.net core 認(rèn)證和授權(quán)實(shí)例詳解5. .NET中實(shí)現(xiàn)對(duì)象數(shù)據(jù)映射示例詳解6. php使用正則驗(yàn)證密碼字段的復(fù)雜強(qiáng)度原理詳細(xì)講解 原創(chuàng)7. ASP.NET MVC把數(shù)據(jù)庫(kù)中枚舉項(xiàng)的數(shù)字轉(zhuǎn)換成文字8. 如何使用ASP.NET Core 配置文件9. jscript與vbscript 操作XML元素屬性的代碼10. 基于javaweb+jsp實(shí)現(xiàn)企業(yè)車輛管理系統(tǒng)
