Skip to content

Commit 3a2ca12

Browse files
authored
Allow itemKey to be a function (#18)
* 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.
1 parent 7f2c70b commit 3a2ca12

File tree

1 file changed

+10
-3
lines changed

1 file changed

+10
-3
lines changed

src/components/Sortable.vue

Lines changed: 10 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
<script setup lang="ts">
2-
import { ref, PropType, watch, onUnmounted, Prop } from "vue";
2+
import { ref, PropType, watch, onUnmounted, computed } from "vue";
33
import Sortable, { SortableOptions } from "sortablejs";
44
55
const props = defineProps({
@@ -33,7 +33,9 @@ const props = defineProps({
3333
},
3434
/** The name of the key present in each item in the list that corresponds to a unique value. */
3535
itemKey: {
36-
type: String as PropType<string>,
36+
type: [String, Function] as PropType<
37+
string | ((item: any) => string | number | Symbol)
38+
>,
3739
default: "",
3840
required: true,
3941
},
@@ -62,6 +64,11 @@ const emit = defineEmits<{
6264
6365
const containerRef = ref<HTMLElement | null>(null);
6466
const sortable = ref<Sortable | null>(null);
67+
const getKey = computed(() => {
68+
if (typeof props.itemKey === "string")
69+
return (item: any) => item[props.itemKey as string];
70+
return props.itemKey;
71+
});
6572
6673
watch(containerRef, (newDraggable) => {
6774
if (newDraggable) {
@@ -105,7 +112,7 @@ onUnmounted(() => {
105112
<component ref="containerRef" :is="$props.tag" :class="$props.class">
106113
<slot
107114
v-for="(item, index) of list"
108-
:key="item[$props.itemKey!]"
115+
:key="getKey(item)"
109116
:element="item"
110117
:index="index"
111118
name="item"

0 commit comments

Comments
 (0)