import {Directive,App} from "vue";
const getPxVal =(str: string) => {
if(str && str.endsWith('px')) {
return parseInt(str.substring(0,str.length-2))
} else {
return 0
}
}
interface DragBind {
mousemove: (e :MouseEvent) => void
mousedown: (e :MouseEvent) => void
mouseup: (e :MouseEvent) => void
}
const myDirective: Directive = {
mounted(el: HTMLElement, binding, vnode, prevVnode) {
console.log(binding)
const title = el.children[0] as HTMLElement
if (!title){
return
}
let dragging: false;
let dragPoint: {x:number,y:number,left:number,top: number}
const dragBind = binding as unknown as DragBind
dragBind.mousemove = (e: MouseEvent) => {
const x = e.clientX - dragPoint.x
const y = e.clientY - dragPoint.y
debugger
if(dragPoint.left+x<=0){
el.style.left = '0px'
}else{
if(dragPoint.left+x+el.clientWidth >= document.documentElement.clientWidth){
el.style.left = (document.documentElement.clientWidth - el.clientWidth) +'px'
}else{
el.style.left = (dragPoint.left + x) +'px'
}
}
if(dragPoint.top+y<=0){
el.style.top = '0px'
}else{
if(dragPoint.top+y+el.clientHeight >= document.documentElement.clientHeight){
el.style.top = (document.documentElement.clientHeight - el.clientHeight) +'px'
}else{
el.style.top = (dragPoint.top + y) +'px'
}
}
}
dragBind.mousedown = (e: MouseEvent)=>{
if (!dragging) {
window.addEventListener('mousemove',dragBind.mousemove)
}
dragPoint = {
x: e.clientX,y: e.clientY,left:getPxVal(el.style.left),top: getPxVal(el.style.top),
}
}
dragBind.mouseup = (e: MouseEvent) => {
console.log('mouseup')
window.removeEventListener('mousemove',dragBind.mousemove)
dragging = false
}
el.addEventListener('mousedown',dragBind.mousedown)
el.addEventListener('mouseup',dragBind.mouseup)
},
unmounted(el: HTMLElement, binding) {
const dragBind = binding as unknown as DragBind
window.removeEventListener('mousemove',dragBind.mousemove)
console.log('卸载')
}
}
const applyApp = (app: App)=> {
app.directive('dialog-x',myDirective)
}
export {
applyApp
}