vue擁用很多強大的指令,但有些邏輯無法實現,所以vue提供了directive自定義指令由開發者任意擴展,本文自定義一個拖拽功能的指令
一、效果圖如下

二、指令的使用:自定義拖拽的初始位置(left,top),不傳參默認為0,即在左上角


三、思路解析
1、首先需要清楚指令里面有哪些參數,第一個參數el是綁定元素

2、第二個參數一個對象(包含指令name,value,argument等),綁定指令那里傳參,這里接收參數並寫邏輯

四、附上具體實現代碼
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
.box {
width: 120px;
height: 120px;
background-color: #eee;
}
</style>
</head>
<body>
</body>
<div id="app">
<button v-drag>點擊</button>
<div class="box" v-drag:[place]></div>
</div>
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<script>
Vue.directive('drag', {
inserted: function (el, bancing) {
console.log(bancing)**
if (bancing.arg) {
**l = bancing.arg.left;
t = bancing.arg.top;
} else {**
l = t = 0;**
}**
el.style.position = 'absolute';
**el.style.left = l + 'px';
el.style.top = t + 'px';
el.onmousedown = function (e) {
var x = e.offsetX;
var y = e.offsetY;
document.onmousemove = function (eve) {
var left = eve.clientX - x;
var top = eve.clientY - y;
el.style.left = left + 'px';
**el.style.top = top + 'px';**
}
document.onmouseup = function (eve) {**
document.onmousemove = null;**
document.onmouseup = null;**
}
}
}
})
new Vue({
el: '#app',
data: {
place: {
left: 100,
top: 100
}
}
})
</script>
</html>
