vue-自定义拖拽
1、新建 directives.js 文件
import draggable from './draggable'
// 自定义指令
const directives = {
draggable
}
export default {
install(Vue) {
Object.keys(directives).forEach((key) => {
Vue.directive(key, directives[key])
})
},
}
2、在
main.js 引入并调用import Directives from '@/assets/js/directives'
Vue.use(Directives)
指令定义函数提供了几个钩子函数(可选):
- bind: 只调用一次,指令第一次绑定到元素时调用,可以定义一个在绑定时执行一次的初始化动作。
- inserted: 被绑定元素插入父节点时调用(父节点存在即可调用,不必存在于 document 中)。
- update: 被绑定元素所在的模板更新时调用,而不论绑定值是否变化。通过比较更新前后的绑定值。
- componentUpdated: 被绑定元素所在模板完成一次更新周期时调用。
- unbind: 只调用一次, 指令与元素解绑时调用。
3、v-draggable
- 设置需要拖拽的元素为相对定位,其父元素为绝对定位。
- 鼠标按下
(onmousedown)时记录目标元素当前的left和top值。 - 鼠标移动
(onmousemove)时计算每次移动的横向距离和纵向距离的变化值,并改变元素的left和top值 - 鼠标松开
(onmouseup)时完成一次拖拽
const draggable = {
inserted: function (el) {
el.style.cursor = 'move'
el.onmousedown = function (e) {
let disx = e.pageX
let disy = e.pageY
document.onmousemove = function (e) {
let x = e.pageX - disx
let y = e.pageY - disy
let maxX = document.body.clientWidth - parseInt(window.getComputedStyle(el).width)
let maxY = document.body.clientHeight - parseInt(window.getComputedStyle(el).height)
if (x < 0) {
x = 0
} else if (x > maxX) {
x = maxX
}
if (y < 0) {
y = 0
} else if (y > maxY) {
y = maxY
}
el.style.left = x + 'px'
el.style.top = y + 'px'
}
document.onmouseup = function () {
document.onmousemove = document.onmouseup = null
}
}
},
}
export default draggable
浙公网安备 33010602011771号