在 ElementUI 2.0 样式框架库中 el-dialog 弹窗并不能实现拖拽,虽然这个问题在 Element-Plus 中已经实现。但是对于框架库中使用ElementUI的用户,拖拽的效果则需要自行实现。
一、指令式实现
dialogDraggable.js
// 自定义指令:实现element-ui对话框dialog拖拽功能
import Vue from 'vue'
// v-draggable: 弹窗拖拽
Vue.directive('draggable', {
update(el, binding, vnode, oldVnode) {
if (!binding.value) return
const dialogHeaderEl = el.querySelector('.el-dialog__header')
const dragDom = el.querySelector('.el-dialog')
dialogHeaderEl.style.cursor = 'move'
// 获取原有属性 ie dom元素.currentStyle 火狐谷歌 window.getComputedStyle(dom元素, null);
const sty = dragDom.currentStyle || window.getComputedStyle(dragDom, null)
dialogHeaderEl.onmousedown = (e) => {
// 鼠标按下,获得鼠标在盒子内的坐标(鼠标在页面的坐标 减去 对话框的坐标),计算当前元素距离可视区的距离
const disX = e.clientX - dialogHeaderEl.offsetLeft
const disY = e.clientY - dialogHeaderEl.offsetTop
// 获取到的值带px 正则匹配替换
let styL, styT
// 注意在ie中 第一次获取到的值为组件自带50% 移动之后赋值为px
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) {
// 鼠标移动,用鼠标在页面的坐标 减去 鼠标在盒子里的坐标,获得模态框的left和top值
// 通过事件委托,计算移动的距离
const l = e.clientX - disX
const t = e.clientY - disY
// 移动当前元素
dragDom.style.left = `${l + styL}px`
// eslint-disable-next-line
if ((t + styT) < -600) {
dragDom.style.top = '-600px'
} else {
dragDom.style.top = `${t + styT}px`
}
// 将此时的位置传出去
// binding.value({x:e.pageX,y:e.pageY})
}
document.onmouseup = function (e) {
// 鼠标弹起,移除鼠标移动事件
document.onmousemove = null
document.onmouseup = null
}
}
}
})
在 main.js 中引入:
import Vue from 'vue'
import ElementUI from 'element-ui'
import 'element-ui/lib/theme-chalk/index.css'
import locale from 'element-ui/lib/locale/lang/zh-CN' // lang i18n
import App from './App'
import store from './store'
import router from './router'
Vue.use(ElementUI, { locale })
import '@/utils/dialogDraggable.js'// 全局引入v-draggable自定义指令
Vue.config.productionTip = false
new Vue({
el: '#app',
router,
store,
render: h => h(App)
})
Vue.use(axios)
二、二次封装Dialog
自定义组件二次封装el-dialog,在自定义封装的组件中设置props(如draggable),当属性值为 true 时,将dialogDraggable.js中监听拖拽的逻辑进行实现。

1万+

被折叠的 条评论
为什么被折叠?



