Sortable.js 是一个 JavaScript 库,用于实现拖放排序功能。在 Vue3 中使用 Sortable.js 可以通过以下步骤:

  1. 安装 Sortable.js 和 @shopify/draggable 库
npm install sortablejs @shopify/draggable
  1. 在 Vue 项目中引入 Sortable.js 和 @shopify/draggable 库
import Sortable from 'sortablejs';
import { Draggable } from '@shopify/draggable';
  1. 创建一个 Vue 组件,并在组件中定义一个 DOM 元素用于实现拖放排序功能
<template>
  <ul ref='list'>
    <li v-for='(item, index) in items' :key='index'>{{ item }}</li>
  </ul>
</template>
  1. 在组件的 mounted 生命周期中,初始化 Sortable.js 和 @shopify/draggable 库,并设置相关配置
mounted() {
  const el = this.$refs.list;
  const sortable = Sortable.create(el, {
    animation: 150,
    onEnd: this.onSortEnd,
  });
  const draggable = new Draggable.Sortable(el, {
    draggable: 'li',
  });
},
methods: {
  onSortEnd(event) {
    // 在拖放结束后,更新数据
    const newIndex = event.newIndex;
    const oldIndex = event.oldIndex;
    const items = [...this.items];
    const item = items.splice(oldIndex, 1)[0];
    items.splice(newIndex, 0, item);
    this.items = items;
  },
},
  1. 在 Vue 组件中定义 items 数据,用于存储排序后的数据
data() {
  return {
    items: ['Item 1', 'Item 2', 'Item 3', 'Item 4', 'Item 5'],
  };
},
  1. 最后,在 Vue 模板中使用该组件即可实现拖放排序功能
<template>
  <div>
    <sortable-list></sortable-list>
  </div>
</template>
Vue3 中使用 Sortable.js 实现拖放排序

原文地址: https://www.cveoy.top/t/topic/oLU4 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录