创建一个js文件,这里我创建的是dialogDrag.js
import Vue from 'vue'
Vue.directive('dialogDrag', {
bind: function (el) {
const dialogHeaderEl = el.querySelector('.el-dialog__header')
const dragDom = el.querySelector('.el-dialog')
dialogHeaderEl.style.cursor = 'move'
const sty = dragDom.currentStyle || window.getComputedStyle(dragDom, null)
dialogHeaderEl.onmousedown = e => {
const disX = e.clientX - dialogHeaderEl.offsetLeft
const disY = e.clientY - dialogHeaderEl.offsetTop
let styL, styT
if (sty.left.includes('%')) {
styL = +document.body.clientWidth * (+sty.left.replace(/\%/g, '') / 100)
styT = +document.body.clientHeight * (+sty.top.replace(/\%/g, '') / 100)
} else {
styL = +sty.left.replace(/\px/g, '')
styT = +sty.top.replace(/\px/g, '')
}
document.onmousemove = function (e) {
const l = e.clientX - disX
const t = e.clientY - disY
dragDom.style.left = `${l + styL}px`
dragDom.style.top = `${t + styT}px`
}
document.onmouseup = function () {
document.onmousemove = null
document.onmouseup = null
}
}
}
})
在main.js中引入
import '@/utils/dialogDrag'
在使用弹窗的地方使用即可,直接v-dialogDrag.
<el-dialog
title="提示"
:visible.sync="dialogVisible"
width="30%"
:before-close="handleClose"
v-dialogDrag
>
<span>这是一段信息</span>
<span slot="footer" class="dialog-footer">
<el-button @click="dialogVisible = false">取 消</el-button>
<el-button type="primary" @click="dialogVisible = false">确 定</el-button>
</span>
</el-dialog>