- // draggable.js
- export default {
- // 定义 Vue 插件
- install(Vue) {
- Vue.directive('draggable', { // 全局指令名为 v-draggable
- inserted(el) {
- el.onmousedown = function (ev) {
- // 获取鼠标按下时的偏移量(鼠标位置 - 元素位置)
- const disX = ev.clientX - el.offsetLeft
- const disY = ev.clientY - el.offsetTop
- document.onmousemove = function (ev) {
- // 获取鼠标实时移动时,元素的位置(鼠标实时位置 - 偏移量)
- const l = ev.clientX - disX
- const t = ev.clientY - disY
- // 实时设置元素位置
- el.style.left = l + 'px'
- el.style.top = t + 'px'
- }
- document.onmouseup = function () {
- // 鼠标抬起时,销毁移动事件和鼠标抬起事件
- document.onmousemove = document.onmouseup = null
- }
- }
- }
- })
- }
- }
- // main.js
- import draggable from '@/utils/draggable.js'
- Vue.use(draggable)
- <div v-draggable>
- <div>内容div>
- div>
-
- //鼠标样式
- cursor: move;
创建js文件
- // draggable.js
- export default {
- // 定义 Vue 插件
- install(Vue) {
- Vue.directive('draggable', { // 全局指令名为 v-draggable
- mounted(el) {
- el.onmousedown = function (e) {
- // 获取鼠标按下时的偏移量(鼠标位置 - 元素位置)
- const disX = e.clientX - el.offsetLeft
- const disY = e.clientY - el.offsetTop
- document.onmousemove = function (e) {
- // 获取鼠标实时移动时,元素的位置(鼠标实时位置 - 偏移量)
- const l = e.clientX - disX
- const t = e.clientY - disY
- // 实时设置元素位置
- el.style.left = l + 'px'
- el.style.top = t + 'px'
- }
- document.onmouseup = function () {
- // 鼠标抬起时,销毁移动事件和鼠标抬起事件
- document.onmousemove = document.onmouseup = null
- }
- }
- }
- })
- }
- }
全局注册
- //main.js
- import draggable from './utils/draggable';
-
- const app = createApp(App);
- app
- .use(router)
- .use(draggable)
- .mount('#app')