一、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>
