Vue:制作一个通用的拖拽组件
Posted BennuCTech
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Vue:制作一个通用的拖拽组件相关的知识,希望对你有一定的参考价值。
废话不多说,直接上代码
FloatContainer.vue
<script setup>
import onMounted, onUnmounted from "vue";
const dragId = `drag-div-$new Date().getTime()`;
let dragDiv;
onMounted(() =>
dragDiv = document.getElementById(dragId);
dragDiv.addEventListener("mousedown", mouseDown, false);
);
onUnmounted(() =>
dragDiv?.removeEventListener("mousedown", mouseDown, false);
);
const mouseDown = event =>
if (!dragDiv)
return;
const ev = event || window.event;
const disX = ev.clientX - dragDiv.offsetLeft;
const disY = ev.clientY - dragDiv.offsetTop;
document.onmousemove = moveEvent =>
const moveEv = moveEvent || window.event;
let left = moveEv.clientX - disX;
let top = moveEv.clientY - disY;
//判断边界,以父布局为框
if (left < 0)
left = 0;
if (top < 0)
top = 0;
if (left > dragDiv.parentElement.offsetWidth - dragDiv.offsetWidth)
left = dragDiv.parentElement.offsetWidth - dragDiv.offsetWidth;
if (top > dragDiv.parentElement.offsetHeight - dragDiv.offsetHeight)
top = dragDiv.parentElement.offsetHeight - dragDiv.offsetHeight;
dragDiv.style.left = `$leftpx`;
dragDiv.style.top = `$toppx`;
;
document.onmouseup = upEvent =>
document.onmousemove = null;
document.onmouseup = null;
;
;
</script>
<template>
<div :id="dragId">
<slot></slot>
</div>
</template>
<style scoped lang="less"></style>
这样在使用的时候直接使用即可:
import FloatContainer from “.../FloatContainer.vue”
...
<float-container>
悬浮内容
</float-container>
使用起来非常简单
以上是关于Vue:制作一个通用的拖拽组件的主要内容,如果未能解决你的问题,请参考以下文章