实现效果
自定义指令实现拖拽
文件目录
directives下index.js的文件配置
const drag = {
beforeMount(el, bindling, vnode) {
let oDiv = el // 当前元素
// 禁止选择网页上的文字
document.onselectstart = function () {
return false
}
oDiv.onmousedown = function (e) {
// 鼠标按下,计算当前元素距离可视区的距离
let disX = e.clientX
let disY = e.clientY
let offTop = e.target.offsetTop
let offLeft = e.target.offsetLeft
document.onmousemove = function (e) {
// 通过事件委托,计算移动的距离
let l = e.clientX - disX + offLeft
let t = e.clientY - disY + offTop
const width = document.querySelector('.list').clientWidth
const top = document.querySelector('.list').clientHeight
if (l >= width - 70) {
l = width - 70
} else if (l <= 0) {
l = 0
}
if (t >= top - 70) {
t = top - 70
} else if (t <= 0) {
t = 0
}
oDiv.style.left = l
oDiv.style.top = t
bindling.value[vnode.key].top = t
bindling.value[vnode.key].left = l
}
document.onmouseup = function () {
document.onmousemove = null
document.onmouseup = null
}
return false
}
}
}
// 挂载,注册
const directives = {
install: function (app) {
app.directive('drag', drag)
}
};
export default directives;
main.js文件中的配置
import { createApp } from 'vue'
import App from './App.vue'
import router from './router'
import store from './store'
import Directives from './directives/index'
createApp(App).config.productionTip = false
createApp(App)
.use(store)
.use(router)
.use(Directives)
.mount('#app')
.vue文件中的使用
<dl class="list">
<dd v-for="(item, key) in totallist" :key="key" v-drag="totallist" :style="{ left: item.left+'px', top: item.top+'px' }">
{{ item.title }}
<img :src="item.img" alt="" @click="()=>{setImg(item,key)}" >
</dd>
</dl>
style设置
.list {
margin: 0 auto;
margin-top: 5px;
width: 340px;
height: 390px;
border: 1px solid #ad2a2a;
position: relative;
}
.list dd {
height: 70px;
width: 70px;
background-color: #ad2a2a;
margin: 0;
position: absolute;
}
.list dd img{
width: 50px;
height: 50px;
}