<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<style>
*{margin:0;padding: 0}
#box{
width:100px;
height: 100px;
background: red;
position:absolute;
}
</style>
</head>
<body>
<div id="app">
<div id="box" v-drag.l.t="flag"></div>
</div>//v-drag 中有l t值 则 modifiers中就有这个值
</body>
</html>
<script src="vue.js"></script>
<script>
Vue.directive("drag",(el,{modifiers,value})=>{
console.log(modifiers)
let {l,t} = modifiers;//通过结构赋值 获取l:true t:true
el.addEventListener("mousedown",handleDownCb)
let disX ,disY;
function handleDownCb(e){
disX = e.offsetX;
disY = e.offsetY;
document.addEventListener("mousemove",handleMoveCb);
document.addEventListener("mouseup",handleupCb)
}
function handleMoveCb(e){
let x = e.clientX - disX;
let y = e.clientY - disY;
if((l&&t) && value){
el.style.left = x + ‘px‘;
el.style.top = y + ‘px‘;
return;
}
if(l&&value){
el.style.left = x + ‘px‘;
return;
}
if(t&&value){
el.style.top = y + ‘px‘;
return;
}
}
function handleupCb(){
document.removeEventListener("mousemove",handleMoveCb)
document.removeEventListener("mouseup",handleupCb)
}
})
var vm = new Vue({
el:"#app",
data:{
flag:true
}
})
</script>
原文地址:https://www.cnblogs.com/superclound/p/11247661.html