Skip to content

Commit

Permalink
Allow itemKey to be a function (#18)
Browse files Browse the repository at this point in the history
* fix: remove unused import
* feat: allow itemKey to be a function

This is helpful if the items contained in the provided list are not
objects but lists or other objects from which a key cannot be derived
directly.
  • Loading branch information
kmohrf authored Jul 30, 2022
1 parent 7f2c70b commit 3a2ca12
Showing 1 changed file with 10 additions and 3 deletions.
13 changes: 10 additions & 3 deletions src/components/Sortable.vue
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
<script setup lang="ts">
import { ref, PropType, watch, onUnmounted, Prop } from "vue";
import { ref, PropType, watch, onUnmounted, computed } from "vue";
import Sortable, { SortableOptions } from "sortablejs";
const props = defineProps({
Expand Down Expand Up @@ -33,7 +33,9 @@ const props = defineProps({
},
/** The name of the key present in each item in the list that corresponds to a unique value. */
itemKey: {
type: String as PropType<string>,
type: [String, Function] as PropType<
string | ((item: any) => string | number | Symbol)
>,
default: "",
required: true,
},
Expand Down Expand Up @@ -62,6 +64,11 @@ const emit = defineEmits<{
const containerRef = ref<HTMLElement | null>(null);
const sortable = ref<Sortable | null>(null);
const getKey = computed(() => {
if (typeof props.itemKey === "string")
return (item: any) => item[props.itemKey as string];
return props.itemKey;
});
watch(containerRef, (newDraggable) => {
if (newDraggable) {
Expand Down Expand Up @@ -105,7 +112,7 @@ onUnmounted(() => {
<component ref="containerRef" :is="$props.tag" :class="$props.class">
<slot
v-for="(item, index) of list"
:key="item[$props.itemKey!]"
:key="getKey(item)"
:element="item"
:index="index"
name="item"
Expand Down

1 comment on commit 3a2ca12

@vercel
Copy link

@vercel vercel bot commented on 3a2ca12 Jul 30, 2022

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please sign in to comment.