-
-
Notifications
You must be signed in to change notification settings - Fork 126
/
Copy pathSelect.vue
103 lines (92 loc) · 2.32 KB
/
Select.vue
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
<template>
<div class="form-control w-full">
<label class="label">
<span class="label-text">{{ label }}</span>
</label>
<select v-model="selectedIdx" class="select select-bordered">
<option disabled selected>Pick one</option>
<option v-for="(obj, idx) in items" :key="name != '' ? obj[name] : obj" :value="idx">
{{ name != "" ? obj[name] : obj }}
</option>
</select>
<!-- <label class="label">
<span class="label-text-alt">Alt label</span>
<span class="label-text-alt">Alt label</span>
</label> -->
</div>
</template>
<script lang="ts" setup>
const emit = defineEmits(["update:modelValue", "update:value"]);
const props = defineProps({
label: {
type: String,
default: "",
},
modelValue: {
type: [Object, String] as any,
default: null,
},
items: {
type: Array as () => any[],
required: true,
},
name: {
type: String,
default: "name",
},
valueKey: {
type: String,
default: null,
},
value: {
type: String,
default: "",
},
compareKey: {
type: String,
default: null,
},
});
const selectedIdx = ref(-1);
const internalSelected = useVModel(props, "modelValue", emit);
const internalValue = useVModel(props, "value", emit);
watch(
selectedIdx,
newVal => {
if (newVal === -1) {
return;
}
if (props.value) {
internalValue.value = props.items[newVal][props.valueKey];
}
internalSelected.value = props.items[newVal];
},
{ immediate: true }
);
watch(
[internalSelected, () => props.value],
() => {
if (props.valueKey) {
const idx = props.items.findIndex(item => compare(item, internalValue.value));
selectedIdx.value = idx;
return;
}
const idx = props.items.findIndex(item => compare(item, internalSelected.value));
selectedIdx.value = idx;
},
{ immediate: true }
);
function compare(a: any, b: any): boolean {
if (a === b) {
return true;
}
if (props.valueKey) {
return a[props.valueKey] === b;
}
// Try compare key
if (props.compareKey && a && b) {
return a[props.compareKey] === b[props.compareKey];
}
return JSON.stringify(a) === JSON.stringify(b);
}
</script>