1.utils文件夾下創建dialog.js文件
1 import Vue from 'vue' 2 3 // v-dialogDrag: 彈窗拖拽 4 Vue.directive('dialogDrag', { 5 bind(el, binding, vnode, oldVnode) { 6 const dialogHeaderEl = el.querySelector('.el-dialog__header') 7 const dragDom = el.querySelector('.el-dialog') 8 dialogHeaderEl.style.cursor = 'move' 9 10 // 獲取原有屬性 ie dom元素.currentStyle 火狐谷歌 window.getComputedStyle(dom元素, null); 11 const sty = dragDom.currentStyle || window.getComputedStyle(dragDom, null) 12 13 dialogHeaderEl.onmousedown = (e) => { 14 // 鼠標按下,計算當前元素距離可視區的距離 15 const disX = e.clientX - dialogHeaderEl.offsetLeft 16 const disY = e.clientY - dialogHeaderEl.offsetTop 17 18 // 獲取到的值帶px 正則匹配替換 19 let styL, styT 20 21 // 注意在ie中 第一次獲取到的值為組件自帶50% 移動之后賦值為px 22 if (sty.left.includes('%')) { 23 styL = +document.body.clientWidth * (+sty.left.replace(/\%/g, '') / 100) 24 styT = +document.body.clientHeight * (+sty.top.replace(/\%/g, '') / 100) 25 } else { 26 styL = +sty.left.replace(/\px/g, '') 27 styT = +sty.top.replace(/\px/g, '') 28 } 29 30 document.onmousemove = function(e) { 31 // 通過事件委托,計算移動的距離 32 const l = e.clientX - disX 33 const t = e.clientY - disY 34 35 // 移動當前元素 36 dragDom.style.left = `${l + styL}px` 37 dragDom.style.top = `${t + styT}px` 38 39 // 將此時的位置傳出去 40 // binding.value({x:e.pageX,y:e.pageY}) 41 } 42 43 document.onmouseup = function(e) { 44 document.onmousemove = null 45 document.onmouseup = null 46 } 47 } 48 } 49 })
2.在main.js中全局引用
1 import './utils/dialog'
3.使用方法:給 el-dialog 添加 v-dialogDrag屬性
1 <el-dialog v-dialogDrag></el-dialog>