今天我们来做一个用vue的自定义指令来实现拖拽功能,首先来看图
下面来进行详细的教程:
上面这张图是我们所需要用到的三个鼠标事件
使用自定义指令 v-drag
<template>
<div v-drag class="w">hello vue!</div>
</template>
<!--一定不要忘记在css中添加 position: absolute;-->
在script中注册自定义指令
// 使用directives注册v-focus指令
directives: {
drag: {
inserted(el) {
el.onmousedown = (e) => {
let x = e.clientX - el.offsetLeft;
let y = e.clientY - el.offsetTop;
document.onmousemove = (e) => {
let xx = e.clientX - x + "px";
let yy = e.clientY - y + "px";
el.style.left = xx;
el.style.top = yy;
};
el.onmouseup = (e) => {
document.onmousemove = null;
};
};
},
},
mounted() {},
methods: {},
},
就这么简单,搞定,收工