vue element 实现弹窗可拖拽

一、main.js文件同级目录下新建文件directive.js

(并非强制同级,只要main.js引入时路径正确即可,该项目使用的是js,不是ts;如果使用ts的需自行修改ts校验)

 1 //directive.js文件
 2 
 3 import Vue from 'vue'
 4 
 5 // v-dialogDrag: 弹窗拖拽
 6 Vue.directive('dialogDrag', {
 7   bind(el, binding, vnode, oldVnode) {
 8     const dialogHeaderEl = el.querySelector('.el-dialog__header')
 9     const dragDom = el.querySelector('.el-dialog')
10     dialogHeaderEl.style.cursor = 'move'
11 
12     // 获取原有属性 ie dom元素.currentStyle 火狐谷歌 window.getComputedStyle(dom元素, null);
13     const sty = dragDom.currentStyle || window.getComputedStyle(dragDom, null)
14 
15     dialogHeaderEl.onmousedown = (e) => {
16       // 鼠标按下,计算当前元素距离可视区的距离
17       const disX = e.clientX - dialogHeaderEl.offsetLeft
18       const disY = e.clientY - dialogHeaderEl.offsetTop
19 
20       // 获取到的值带px 正则匹配替换
21       let styL, styT
22 
23       // 注意在ie中 第一次获取到的值为组件自带50% 移动之后赋值为px
24       if (sty.left.includes('%')) {
25         styL = +document.body.clientWidth * (+sty.left.replace(/\%/g, '') / 100)
26         styT = +document.body.clientHeight * (+sty.top.replace(/\%/g, '') / 100)
27       } else {
28         styL = +sty.left.replace(/\px/g, '')
29         styT = +sty.top.replace(/\px/g, '')
30       }
31 
32       document.onmousemove = function(e) {
33         // 通过事件委托,计算移动的距离
34         const l = e.clientX - disX
35         const t = e.clientY - disY
36 
37         // 移动当前元素
38         dragDom.style.left = `${l + styL}px`
39         dragDom.style.top = `${t + styT}px`
40 
41         // 将此时的位置传出去
42         // binding.value({x:e.pageX,y:e.pageY})
43       }
44 
45       document.onmouseup = function(e) {
46         document.onmousemove = null
47         document.onmouseup = null
48       }
49     }
50   }
51 })
52 
53 // v-dialogDragWidth: 弹窗宽度拖大 拖小
54 Vue.directive('dialogDragWidth', {
55   bind(el, binding, vnode, oldVnode) {
56     const dragDom = binding.value.$el.querySelector('.el-dialog')
57 
58     el.onmousedown = (e) => {
59       // 鼠标按下,计算当前元素距离可视区的距离
60       const disX = e.clientX - el.offsetLeft
61 
62       document.onmousemove = function(e) {
63         e.preventDefault() // 移动时禁用默认事件
64 
65         // 通过事件委托,计算移动的距离
66         const l = e.clientX - disX
67         dragDom.style.width = `${l}px`
68       }
69 
70       document.onmouseup = function(e) {
71         document.onmousemove = null
72         document.onmouseup = null
73       }
74     }
75   }
76 })

二、main.js引入

import './directives.js' // 拖拽弹窗,在需要用到拖拽功能的弹窗标签上加v-dialogDrag

三、在需要用到拖拽功能的弹窗标签上加v-dialogDrag,即可!示例:

 

<template>
  <el-dialog
    v-dialogDrag
    :visible.sync="dialogVisible"
    width="700px"
    title="新增编辑"
  >
    
  </el-dialog>
</template>

 

posted @ 2020-10-21 16:28  辰熙ali  阅读(1969)  评论(0编辑  收藏  举报