当前位置:首页 > VUE

vue实现左右拖拽

2026-03-10 01:41:04VUE

实现左右拖拽功能

在Vue中实现左右拖拽功能可以通过监听鼠标事件和使用CSS变换来实现。以下是具体的实现方法。

使用鼠标事件监听

通过监听mousedownmousemovemouseup事件来跟踪拖拽行为。

<template>
  <div
    class="draggable"
    @mousedown="startDrag"
    @mousemove="onDrag"
    @mouseup="stopDrag"
    @mouseleave="stopDrag"
    :style="{ left: position.x + 'px', top: position.y + 'px' }"
  >
    拖拽我
  </div>
</template>

<script>
export default {
  data() {
    return {
      isDragging: false,
      startPos: { x: 0, y: 0 },
      position: { x: 0, y: 0 }
    };
  },
  methods: {
    startDrag(e) {
      this.isDragging = true;
      this.startPos = {
        x: e.clientX - this.position.x,
        y: e.clientY - this.position.y
      };
    },
    onDrag(e) {
      if (!this.isDragging) return;
      this.position = {
        x: e.clientX - this.startPos.x,
        y: e.clientY - this.startPos.y
      };
    },
    stopDrag() {
      this.isDragging = false;
    }
  }
};
</script>

<style>
.draggable {
  position: absolute;
  width: 100px;
  height: 100px;
  background-color: #42b983;
  cursor: move;
  user-select: none;
}
</style>

使用第三方库

对于更复杂的拖拽需求,可以使用第三方库如vuedraggablesortablejs

安装vuedraggable

npm install vuedraggable

示例代码:

<template>
  <div>
    <draggable v-model="list" @start="drag=true" @end="drag=false">
      <div v-for="element in list" :key="element.id">
        {{ element.name }}
      </div>
    </draggable>
  </div>
</template>

<script>
import draggable from 'vuedraggable';

export default {
  components: { draggable },
  data() {
    return {
      list: [
        { id: 1, name: 'Item 1' },
        { id: 2, name: 'Item 2' },
        { id: 3, name: 'Item 3' }
      ]
    };
  }
};
</script>

使用CSS拖拽

对于简单的拖拽效果,可以使用CSS的drag属性,但兼容性较差。

<template>
  <div draggable="true" @dragstart="handleDragStart">
    拖拽我
  </div>
</template>

<script>
export default {
  methods: {
    handleDragStart(e) {
      e.dataTransfer.setData('text/plain', '拖拽内容');
    }
  }
};
</script>

注意事项

确保拖拽元素具有position: absoluteposition: relative样式,以便正确计算位置。

拖拽过程中避免触发文本选择,可以通过CSS设置user-select: none

vue实现左右拖拽

对于移动端支持,需要额外处理touchstarttouchmovetouchend事件。

标签: 拖拽vue
分享给朋友:

相关文章

vue实现用户信息表

vue实现用户信息表

Vue 实现用户信息表的方法 使用 Vue CLI 创建项目 安装 Vue CLI 并初始化项目: npm install -g @vue/cli vue create user-info-tabl…

vue全选实现

vue全选实现

Vue 全选实现方法 在 Vue 中实现全选功能通常涉及数据绑定和事件处理。以下是几种常见的实现方式: 基础实现方式 <template> <div> <i…

vue实现分类

vue实现分类

Vue实现分类功能的方法 使用v-for和计算属性 通过计算属性对数据进行分类处理,结合v-for渲染分类后的列表。示例代码: <template> <div>…

vue实现监听

vue实现监听

监听数据变化 在Vue中,可以通过watch选项或$watch方法监听数据的变化。watch适用于组件选项内声明式监听,$watch适用于动态监听。 // 选项式API export default…

vue实现dag

vue实现dag

Vue实现DAG(有向无环图) 在Vue中实现DAG(Directed Acyclic Graph,有向无环图)通常涉及数据结构的建模、可视化渲染以及交互逻辑处理。以下是关键实现步骤和示例代码: 数…

vue cli 实现

vue cli 实现

Vue CLI 实现步骤 安装 Vue CLI 确保 Node.js 版本在 8.9 或以上。通过 npm 全局安装 Vue CLI: npm install -g @vue/cli 创建新项目 使…