/vue-sortablejs

Sortablejs behavior for Vue 3

Primary LanguageVueMIT LicenseMIT

@bedard/vue-sortablejs

Build status NPM Bundle size License

A minimalist interface for Sortablejs, no components required.

View live sandbox →

Installation

Install via npm

npm install @bedard/vue-sortablejs

Install via cdn

<script src="https://unpkg.com/@bedard/vue-sortablejs" type="module"></script>

Basic use

Register useSortable with a container, and render the array with a v-for loop

<template>
  <div ref="container" :key="sortKey">
    <div v-for="item in items">
      {{ item }}
    </div>
  </div>
</template>

<script setup>
import { ref } from 'vue'
import { sort, useSortable } from '@bedard/vue-sortablejs'

const container = ref()

const { sortKey } = useSortable(container, {
  onSort: e => sort(items, e),
})
</script>

Here is a breakdown of what's happening

  1. an outer container ref is created
  2. a unique sortKey is attached to that container
  3. the sort helper syncs state when onSort fires

Advanced use

Reactivity

All options support reactivity, and Sortablejs instances are refreshed on change.

const disabled = ref(false)

const sortable = useSortable(container, {
  disabled,
})

View all available options →

Shared lists

Use transfer to move items from one array to another

import { sort, transfer, useSortable } from '@bedard/vue-sortablejs'

const first = useSortable(firstContainer, {
  group: 'shared',
  onAdd: e => transfer(from, to, e),
})

const second = useSortable(secondContainer, {
  group: 'shared',
  onAdd: e => transfer(from, to, e),
})

Manual controls

Sortable instance can be manually created and destroyed

const { createSortableInstances, destroySortableInstances } = useSortable(container)

createSortableInstances() // refresh instances and dom keys

destroySortableInstances() // destroy instances

License

MIT

Copyright (c) 2023-present, Scott Bedard