1.在util文件夹下新建directive.js文件
import Vue from 'vue'
// 自定义指令的格式,名字
Vue.directive('drag', {
bind (el) {
let dragBox = el // 获取当前元素
dragBox.onmousedown = e => {
// 算出鼠标相对元素的位置
let disX = e.clientX - dragBox.offsetLeft
let disY = e.clientY - dragBox.offsetTop
document.onmousemove = e => {
// 用鼠标的位置减去鼠标相对元素的位置,得到元素的位置
let left = e.clientX - disX
let top = e.clientY - disY
// 移动当前元素
dragBox.style.left = left + 'px'
dragBox.style.top = top + 'px'
}
document.onmouseup = () => {
// 鼠标弹起来的时候不再移动
document.onmousemove = null
// 预防鼠标弹起来后还会循环(即预防鼠标放上去的时候还会移动)
document.onmouseup = null
}
}
}
})
2.在main.js中引入该文件,引入之后全局都可以直接使用
import './utils/directive'
3.在需要鼠标拖动的标签上加 v-drag 就可以使用,例如:
<div v-drag></div>