1、config/element文件夹下新建dialogDrag文件
mounted() {
let dragDom = this.$el.getElementsByClassName('el-dialog')[0];
let dialogHeaderDom = this.$el.getElementsByClassName('el-dialog__header')[0];
dialogHeaderDom.style.cursor = 'move'
let mousedown = false;
const sty = dragDom.currentStyle || window.getComputedStyle(dragDom, null)
dialogHeaderDom.onmousedown = (e) => {
mousedown = true; // 鼠标距离弹框的距离
const startLeft = e.clientX - dialogHeaderDom.offsetLeft
const startTop = e.clientY - dialogHeaderDom.offsetTop // 现在弹框的left,top
let styL, styT
if (sty.left.includes('%')) {
styL = +document.body.clientWidth * (+sty.left.replace('%', '') / 100)
styT = +document.body.clientHeight * (+sty.top.replace('%', '') / 100)
} else {
styL = +sty.left.replace('px', '')
styT = +sty.top.replace('px', '')
}
document.onmousemove = function(e) {
if(!mousedown){ return false } // 鼠标移动的距离 + 弹框的left/top
let l = e.clientX - startLeft + styL;
let t = e.clientY - startTop + styT;
const offsetParent = dragDom.offsetParent || document.body;
const maxL = offsetParent.clientWidth - dragDom.clientWidth;
const maxT = offsetParent.clientHeight - dragDom.clientHeight;
if (maxL < l){
l = maxL;
} else if (l < 0 && l * - 1 > startLeft) {
// 向左偏移的距离 l = -startLeft;
} if (t < 0) {
t = 0
} else if (maxT < t){
t = maxT;
}
dragDom.style.left = `${l}px`
dragDom.style.top = `${t}px`
}
document.onmouseup = function(e) {
mousedown = false;
document.onmousemove = null
document.onmouseup = null
}
}
},
2、config/element/index.js文件修改:
import dialogDragMixin from './dialogDrag'
export function installElement(Vue, Element) {
Element.Dialog.mixins.push(dialogDragMixin);
}
3、main.js中引入
import { installElement } from '@/config/element';
installElement(Vue, Element);