• vue实现div拖拽


    首先,你需要在Vue组件中添加一个div元素,并设置它的样式为可拖拽:

    1. class="draggable" @mousedown="startDrag" @mouseup="stopDrag" @mousemove="drag">
  • 然后,在Vue组件的methods中添加以下方法:

    1. data() {
    2. return {
    3. dragging: false,
    4. x: 0,
    5. y: 0,
    6. startX: 0,
    7. startY: 0
    8. };
    9. },
    10. methods: {
    11. startDrag(event) {
    12. this.dragging = true;
    13. this.startX = event.clientX - this.x;
    14. this.startY = event.clientY - this.y;
    15. },
    16. stopDrag() {
    17. this.dragging = false;
    18. },
    19. drag(event) {
    20. if (this.dragging) {
    21. this.x = event.clientX - this.startX;
    22. this.y = event.clientY - this.startY;
    23. }
    24. }
    25. }

    最后,在CSS中添加以下样式

    1. .draggable {
    2. position: absolute;
    3. left: 0;
    4. top: 0;
    5. cursor: move;
    6. }

    移动端:

    对于移动端,需要使用触摸事件来实现拖拽功能。以下是在Vue 3中使用触摸事件实现移动端拖拽的代码示例:

    1. <script>
    2. export default {
    3. data() {
    4. return {
    5. dragging: false,
    6. x: 0,
    7. y: 0,
    8. startX: 0,
    9. startY: 0
    10. };
    11. },
    12. methods: {
    13. startDrag(event) {
    14. this.dragging = true;
    15. this.startX = event.touches[0].clientX - this.x;
    16. this.startY = event.touches[0].clientY - this.y;
    17. },
    18. stopDrag() {
    19. this.dragging = false;
    20. },
    21. drag(event) {
    22. if (this.dragging) {
    23. this.x = event.touches[0].clientX - this.startX;
    24. this.y = event.touches[0].clientY - this.startY;
    25. }
    26. }
    27. }
    28. };
    29. script>
    30. <style>
    31. .draggable {
    32. position: absolute;
    33. left: 0;
    34. top: 0;
    35. cursor: move;
    36. }
    37. style>

    在移动端,我们使用@touchstart、@touchend和@touchmove事件监听器来代替桌面端的鼠标事件。在startDrag和drag方法中,我们使用event.touches[0].clientX和event.touches[0].clientY来获取触摸点的位置。

    这样,你就可以在Vue 3中实现移动端的div拖拽功能了。

  • 相关阅读:
    Java之线程池
    865. 具有所有最深节点的最小子树
    触摸屏实验
    datawhale - 基于术语词典干预的机器翻译挑战赛 (一)
    5. 【线索二叉树】的由来、基本概念、结构体定义、三种遍历线索化、线索二叉树找前驱/后继
    SpringBoot —— 整合RabbitMQ常见问题及解决方案
    [开源]基于Vue的拖拽式数据报表设计器,为简化开发提高效率而生
    嵌入式系统,典型嵌入式系统基本组成,微处理器,嵌入式微处理器,嵌入式软硬件裁减原则,嵌入式实时操作系统
    Android Jetpack系列(一)起始篇:Jetpack 的前世今生
    【MHA】MySQL高可用MHA介绍7-常见问题
  • 原文地址:https://blog.csdn.net/weixin_53841730/article/details/134017441