GithubHelp home page GithubHelp logo

eliottvincent / vue3-sortablejs Goto Github PK

View Code? Open in Web Editor NEW
11.0 2.0 1.0 525 KB

↕️ Re-orderable drag-and-drop lists, via a Vue directive.

Home Page: https://www.npmjs.com/package/vue3-sortablejs

JavaScript 92.44% Vue 7.56%
vue directive drag drag-and-drop draggable drop sortable sortablejs

vue3-sortablejs's Introduction

Vue 3 Sortable

Build Status Version Downloads

Re-orderable drag-and-drop lists, via a Vue directive. Based on and offering all features of Sortable.

[view demo]

Yet another Sortable wrapper

Several Vue wrappers for Sortable exist out there, yet I decided to build another one.

The goal was to have a wrapper that:

  • supports Vue 3
  • is light and easy to maintain
  • works as a directive, for example to conditionally enable / disable the drag-and-drop feature without having to change the whole component
  • doesn't iterate on the data by itself
  • doesn't update the underlying data model (see Order mutation)

As a reference, here are other Sortable wrappers:

Usage

Get Vue 3 Sortable from jsDelivr or UNPKG and use it like this:

<script src="https://unpkg.com/vue@3/dist/vue.global.js"></script>
<script src="https://cdn.jsdelivr.net/npm/sortablejs@latest/Sortable.min.js"></script>
<script src="https://unpkg.com/vue3-sortablejs/dist/vue3-sortablejs.global.js"></script>

<div id="app">
  <div v-sortable>
    <div>a</div>
    <div>b</div>
    <div>c</div>
  </div>
</div>

<script>
  const { createApp } = Vue;

  const app = createApp();

  app.use(sortablejs);

  app.mount("#app");
</script>

Vue 3 Sortable is also available through npm as the vue3-sortablejs package.

Install the package:

npm install --save vue3-sortablejs

Register the plugin in App.vue:

import VueSortable from "vue3-sortablejs";

app.use(VueSortable);

And then use it like this in MyComponent.vue:

<template>
  <h1>My Component</h1>

  <div v-sortable>
    <div>a</div>
    <div>b</div>
    <div>c</div>
  </div>
</template>

Options

You can pass an object of options, in order to affect the behavior of the directive:

  • disabled whether to disable the drag-and-drop behavior
  • options an object containing any Sortable option
<template>
  <div v-sortable="{ disabled: false, options: { animation: 250, easing: 'cubic-bezier(1, 0, 0, 1)' } }">
    <div>a</div>
    <div>b</div>
    <div>c</div>
  </div>
</template>

Events

A custom ready event will be triggered as soon as Sortable is registered on the component. You can use it to access the underlying Sortable instance. As well, you can listen to any native Sortable event.

  • @ready: Sortable is ready and attached to the component
  • @choose: element is chosen
  • @unchoose: element is unchosen
  • @start: element dragging started
  • @end: element dragging ended
  • @add: element is dropped into the list from another list
  • @update: changed sorting within list
  • @sort: called by any change to the list (add / update / remove)
  • @remove: element is removed from the list into another list
  • @filter: attempt to drag a filtered element
  • @move: event when you move an item in the list or between lists
  • @clone: called when creating a clone of element
  • @change: called when dragging element changes position
<template>
  <div v-sortable @ready="onReady" @end="onOrderChange">
    <div>a</div>
    <div>b</div>
    <div>c</div>
  </div>
</template>

<script>
export default {
  methods: {
    onReady(event) {
      console.log(event.sortable);
    },

    onOrderChange(event) {
      console.log(event.oldIndex);
      console.log(event.newIndex);
    }
  }
};
</script>

Order mutation

This wrapper only impacts the actual DOM order, it does not mutate the data order. This avoids a lot of overhead in the code, and gives you the full control on your data.

It is really simple to change the order in your data after an item is dropped:

<template>
  <div v-sortable @end="onOrderChange">
    <div v-for="item in items">
      {{ item }}
    </div>
  </div>

  <span>Items data: {{ items }}</span>
</template>

<script>
export default {
  data() {
    return {
      items: [ "a", "b", "c" ]
    }
  },

  methods: {
    onOrderChange(event) {
      // Remove item from old index
      let item = this.items.splice(event.oldIndex, 1)[0];

      // Insert it at new index
      this.items.splice(event.newIndex, 0, item);
    }
  }
};
</script>

Notes

It is highly recommended to set a key on the children items, to help Sortable track the DOM:

<template>
  <div v-sortable>
    <div key="a">a</div>
    <div key="b">b</div>
    <div key="c">c</div>
  </div>
</template>

In the same way, if you use the group option, it is highly recommended to set a key on the parent itself. Otherwise the DOM managed by Sortable can become out-of-sync with the actual data state. I have noticed this helps a lot when using Sortable with complex components.

The key must be based on the number of items the parent contains. This will force a re-render when an item is added / removed, and make Sortable re-initialize and start from a clean state every time. This may seem a bit hacky, but it's the only way to keep a consistant behavior.

<template>
  <h1>Foo</h1>

  <div v-sortable="{ options: { group: 'items' } }" @end="onOrderChange" :key="fooItems.length">
    <div v-for="item in fooItems" :key="item">
      {{ item }}
    </div>
  </div>

  <h1>Bar</h1>

  <div v-sortable="{ options: { group: 'items' } }" @end="onOrderChange" :key="barItems.length">
    <div v-for="item in barItems" :key="item">
      {{ item }}
    </div>
  </div>
</template>

<script>
export default {
  methods: {
    onOrderChange(event) {
      // Mutate fooItems and barItems
    }
  }
};
</script>

License

vue3-sortablejs is released under the MIT License. See the bundled LICENSE file for details.

vue3-sortablejs's People

Contributors

eliottvincent avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar

vue3-sortablejs's Issues

when setting options , uncaught type error apears

dom tree be like
<div class="user-list" v-sortable="{ options: { handle: '.handle', animation: 200, easing: 'cubic-bezier(0.65, 0, 0.35, 1)' } }" @end="onOrderChange" > <div class="user-list-item" v-for="user in renderList" :key="user.uid"> <div class="handle"> <AIcon category="general" name="drag-dot-vertical"></AIcon> </div> <img class="user-head" :src="user.headIconUrl" /> <div class="user-name">{{ user.nickname }}</div> </div> </div>

Error Message:

Uncaught TypeError: Cannot read properties of null (reading 'options') /node_modules/.vite/deps/vue3-sortablejs.js?v=1770eda3:773:39 TypeError: Cannot read properties of null (reading 'options') at http://192.168.111.212:8080/node_modules/.vite/deps/vue3-sortablejs.js?v=1770eda3:773:39 at Array.some (<anonymous>) at _detectNearestEmptySortable2 (http://192.168.111.212:8080/node_modules/.vite/deps/vue3-sortablejs.js?v=1770eda3:772:13) at HTMLDocument.nearestEmptyInsertDetectEvent2 (http://192.168.111.212:8080/node_modules/.vite/deps/vue3-sortablejs.js?v=1770eda3:838:19)

Add Types

this package is pretty small so i can keep it in my head but typings would be nice.

Update hook with the same options triggers multiple Sortable initializes, which causes errors later

Hey, you did great directive!

One thing is annoying though:

var update = function(element, binding) {
if (binding.value !== binding.oldValue) {
bind(element, binding);
}
};

Options object is compared not deeply here, so every time for some reason directive 'updated' hook is called, though binding options object fields did not change deeply, the reference to options object had changed, so here another Sortable instance creation is triggered, which leads to too many initialized Sortable instances in memory, which all point to same DOM node. And when inital component gets unmounted, only one (last one) Sortable instances gets destroyed, leaving other instances which point to elements no longer in DOM still in memory. So, next time another component initialize directive, Sortable will try to do '_detectNearestEmptySortable' over all it's instances, including the ones no longer pointing to DOM nodes. Which leads to annoying Sortable complainging in console about '_detectNearestEmptySortable' thrown exception.

Though these errors are not critical, because they are related to nodes, no longer present in DOM, this still may cause troubles... You probably may use smth like 'deep-equal' module here or manually do shallow equality check. I used deep-equal lib in the lines above and the errors were gone.

How to do handle in Vue3

How to integrate this into Vue3? Where should I put it?
new Sortable(example5, { handle: '.handle', // handle's class animation: 150 });

The item reference is not passed.

So so far, after some reading, I choose to use this plugin for one of my projects. It was working fine until I encountered something I probably will need some reworking or at least you can give me some direction about this.
So, in vue draggable, I know you can reference the item in v-for, in this plugin because the instantiation begins before v-for, it's impossible to make a reference of the element data it's changing the order. Do you know a way to bypass that?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.