Bind Select's value to make it simpler and more reactive

This commit is contained in:
2021-10-23 15:32:49 +02:00
parent ff4222c05e
commit 89c55c17e2
2 changed files with 11 additions and 16 deletions

View File

@@ -15,16 +15,13 @@
const dispatch = createEventDispatcher() const dispatch = createEventDispatcher()
const defaultOption = options.find(option => option.default) const defaultOption = options.find(option => option.default)
const defaultOptionIndex = options.findIndex(option => option.default)
const selectedOptionIndex = options.findIndex(option => option.selected)
let current: number = selectedOptionIndex let selected = value || options[0].value
let currentOptionEl: HTMLElement $: currentOption = options.find(option => option.value === selected)
$: currentOption = options[current]
// Redefine value from parent (when reset) // Redefine value from parent (when reset)
$: if (value === defaultOption.value) { $: if (value === defaultOption.value) {
current = defaultOptionIndex selected = defaultOption.value
} }
@@ -32,23 +29,21 @@
* When changing select value * When changing select value
*/ */
const handleChange = ({ target: { value }}: any) => { const handleChange = ({ target: { value }}: any) => {
current = options.findIndex(option => option.value === value) const option = options.find(option => option.value === value)
// Dispatch event to parent // Dispatch event to parent
dispatch('change', options[current].value) dispatch('change', option.value)
} }
</script> </script>
<div class="select"> <div class="select">
<slot /> <slot />
<span bind:this={currentOptionEl}> <span>{currentOption.name}</span>
{currentOption.name}
</span>
<select {name} {id} on:change={handleChange}> <select {name} {id} bind:value={selected} on:change={handleChange}>
{#each options as { value, name }, index} {#each options as { value, name }}
<option {value} selected={index === current}> <option {value} selected={value === selected}>
{name} {name}
</option> </option>
{/each} {/each}

View File

@@ -122,7 +122,7 @@
opacity: 0; opacity: 0;
position: absolute; position: absolute;
top: 0; top: 0;
left: 0; left: 8px;
width: 100%; width: 100%;
height: 100%; height: 100%;
cursor: pointer; cursor: pointer;
@@ -321,8 +321,8 @@
bottom: 0; bottom: 0;
right: 0; right: 0;
border-top-left-radius: 8px; border-top-left-radius: 8px;
opacity: 0;
pointer-events: none; pointer-events: none;
opacity: 0;
transform: translate3d(12%, 23%, 0) rotate(-5deg); transform: translate3d(12%, 23%, 0) rotate(-5deg);
transition: opacity 0.4s var(--ease-quart), transform 1.0s var(--ease-quart); transition: opacity 0.4s var(--ease-quart), transform 1.0s var(--ease-quart);
} }