1
0
Fork 1
mirror of https://github.com/hay-kot/homebox.git synced 2024-12-26 08:46:31 +00:00
homebox/frontend/components/Form/Select.vue

104 lines
2.3 KiB
Vue
Raw Normal View History

2022-09-02 17:46:20 +00:00
<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">
2022-09-02 17:46:20 +00:00
<option disabled selected>Pick one</option>
<option v-for="(obj, idx) in items" :key="name != '' ? obj[name] : obj" :value="idx">
{{ name != "" ? obj[name] : obj }}
2022-09-02 17:46:20 +00:00
</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>
2022-10-15 21:56:08 +00:00
const emit = defineEmits(["update:modelValue", "update:value"]);
2022-09-02 17:46:20 +00:00
const props = defineProps({
label: {
type: String,
default: "",
2022-09-02 17:46:20 +00:00
},
modelValue: {
type: [Object, String] as any,
2022-09-02 17:46:20 +00:00
default: null,
},
items: {
type: Array as () => any[],
required: true,
},
name: {
type: String,
default: "name",
2022-09-02 17:46:20 +00:00
},
2022-10-15 21:56:08 +00:00
valueKey: {
type: String,
default: null,
2022-10-15 21:56:08 +00:00
},
value: {
type: String,
default: "",
},
compareKey: {
type: String,
default: null,
},
2022-09-02 17:46:20 +00:00
});
2022-10-14 00:45:18 +00:00
const selectedIdx = ref(-1);
2022-10-15 21:56:08 +00:00
2022-10-14 00:45:18 +00:00
const internalSelected = useVModel(props, "modelValue", emit);
2022-10-16 05:41:27 +00:00
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];
2022-10-16 05:41:27 +00:00
},
{ immediate: true }
2022-10-16 05:41:27 +00:00
);
watch(
[internalSelected, () => props.value],
2022-10-16 05:41:27 +00:00
() => {
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));
2022-10-16 05:41:27 +00:00
selectedIdx.value = idx;
},
{ immediate: true }
2022-10-16 05:41:27 +00:00
);
2022-10-15 21:56:08 +00:00
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);
}
2022-09-02 17:46:20 +00:00
</script>