vue自定义指令实现拖拽

实现效果

自定义指令实现拖拽

文件目录
在这里插入图片描述
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;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

晚时之秋

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值