Bind Select's value to make it simpler and more reactive
This commit is contained in:
@@ -15,16 +15,13 @@
|
||||
|
||||
const dispatch = createEventDispatcher()
|
||||
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 currentOptionEl: HTMLElement
|
||||
$: currentOption = options[current]
|
||||
let selected = value || options[0].value
|
||||
$: currentOption = options.find(option => option.value === selected)
|
||||
|
||||
// Redefine value from parent (when reset)
|
||||
$: if (value === defaultOption.value) {
|
||||
current = defaultOptionIndex
|
||||
selected = defaultOption.value
|
||||
}
|
||||
|
||||
|
||||
@@ -32,23 +29,21 @@
|
||||
* When changing select value
|
||||
*/
|
||||
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('change', options[current].value)
|
||||
dispatch('change', option.value)
|
||||
}
|
||||
</script>
|
||||
|
||||
<div class="select">
|
||||
<slot />
|
||||
|
||||
<span bind:this={currentOptionEl}>
|
||||
{currentOption.name}
|
||||
</span>
|
||||
<span>{currentOption.name}</span>
|
||||
|
||||
<select {name} {id} on:change={handleChange}>
|
||||
{#each options as { value, name }, index}
|
||||
<option {value} selected={index === current}>
|
||||
<select {name} {id} bind:value={selected} on:change={handleChange}>
|
||||
{#each options as { value, name }}
|
||||
<option {value} selected={value === selected}>
|
||||
{name}
|
||||
</option>
|
||||
{/each}
|
||||
|
||||
Reference in New Issue
Block a user