Vue全局指令实现拖拽
大约 1 分钟
Vue全局指令实现拖拽
封装全局指令
在项目的 src 目录下创建 src/utils/candrag.js 文件,代码如下:
export default {
// 定义 Vue 插件
install(Vue) {
Vue.directive('candrag', { // 全局指令名为 v-candrag
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 = null
document.onmouseup = null
}
}
}
})
}
}
使用插件
在 src/main.js 入口文件引入包含全局拖拽指令的插件,代码如下:
import Vue from 'vue'
import App from './App.vue'
import router from './router'
import candrag from '@/utils/candrag.js' // 引入插件
// 使用插件
Vue.use(candrag)
new Vue({
router,
render: h => h(App)
}).$mount('#app')
在组件中使用拖拽指令
在任意的组件文件中可以通过 v-candrag 指令赋予元素可拖拽的能力,代码如下:
<template>
<div class="drag-container">
<div class="drag-div" v-candrag></div>
</div>
</template>
<script>
// javascript脚本代码...
</script>
<style scoped>
.drag-container {
width: 100%;
height: 100%;
position: relative; /* 把拖拽元素父元素设置为相对定位,非常重要!!! */
background-color: bisque;
}
.drag-div {
position: absolute; /* 把拖拽元素设置为绝对定位,非常重要!!! */
width: 300px;
height: 300px;
background-color: pink;
}
</style>
