当前位置: 首页 > news >正文

vue2实现元素拖拽

直接使用vue-draggable插件更好
以下是模仿代码

<!--  -->
<template><div><button v-on:click="shuffle">Shuffle</button><transition-group name="flip-list" tag="ul" class="box" ref="box"><liv-for="(item, index) in list":key="item.text"class="list":class="item.classList"draggable@dragstart="dragstart(item)"@dragenter="dragenter(item)"@dragend="dragend">{{ item.text }}</li></transition-group><div>12312</div></div>
</template><script>
// 记录被拖动的元素
let source;
export default {data() {return {list: [{ text: 1 }, { text: 2 }, { text: 3 }, { text: 4 }, { text: 5 }, { text: 6 }, { text: 7 }, { text: 8 }, { text: 9 }, { text: 10 }],};},created() {this.list = this.list.map((item) => {return {...item,classList: [],};});},methods: {shuffle: function () {this.list.sort(() => Math.random() - 0.5);},dragstart(e) {source = e;setTimeout(() => {e.classList.push("moveing");}, 0);},dragenter(e) {if (e.text === source.text) return;this.changeSort(e);},dragend(e) {let _soucre = this.list.find((item) => item.text === source.text);let classIndex = _soucre.classList.findIndex((item) => item === "moveing");_soucre.classList.splice(classIndex, 1);source = null},// 与soucre元素交换位置changeSort(e) {const targetIndex = this.list.findIndex((item) => item.text === e.text);const sourceIndex = this.list.findIndex((item) => item.text === source.text);this.list.splice(targetIndex, 1, ...this.list.splice(sourceIndex, 1, this.list[targetIndex]));},},
};
</script>
<style lang="scss" scoped>
.box {display: flex;padding: 20px;
}
.list {display: flex;justify-content: center;align-items: center;width: 100px;height: 50px;margin-right: 10px;background-color: skyblue;
}.moveing {background-color: gray;
}
.flip-list-move {transition: transform 0.5s;
}.li {display: flex;justify-content: center;align-items: center;width: 100px;height: 50px;margin-bottom: 10px;background-color: skyblue;
}
</style>

相关文章:

  • 自由开发者计划 002:创建一个贷款计算器的微信小程序
  • Elasticsearch 写入性能优化有哪些常见手段?
  • 2025版 JavaScript性能优化实战指南从入门到精通
  • 【机器学习基础】机器学习入门核心算法:线性回归(Linear Regression)
  • 用vue canvas画一个能源电表和设备的监测图
  • 《STL--string的使用及其底层实现》
  • (第94天)OGG 微服务搭建 Oracle 19C CDB 架构同步
  • Openwrt下使用ffmpeg配合自建RTSP服务器实现推流
  • vite搭建vue3项目及相关配置
  • Python----循环神经网络(Word2Vec的优化)
  • 数据库表索引维护策略
  • Spring概念问题详解
  • 珠宝课程小程序源码介绍
  • 基于 WebRTC 的一对一屏幕共享项目(一)——项目简介
  • Google Prompt Tuning:文本嵌入优化揭秘
  • tf 重排 切分 逆排列
  • 鸿蒙Flutter实战:22-混合开发详解-2-Har包模式引入
  • Flutter 3.32 新特性
  • 旧物回收小程序:让闲置焕发光彩,为生活增添价值
  • docker network 自定义网络配置与管理指南
  • 做塑料哪个网站好/惠州seo排名
  • 工程公司名称大全集最新免费/大连做优化网站哪家好
  • 网站怎么做才能被百度收录/百度推广电话客服
  • 手机友好型网站/网络推广公司运营
  • 唐山哪家做网站好/怎么让某个关键词排名上去
  • 天津红桥网站建设/网站seo技术能不能赚钱