I was wondering whether there are any best practises on when to use a switch
/case
assignment vs. using if
/ else if
logic blocks in svelte?
E.g. if I have an enum
export enum Status {
riding = "RIDING",
arrived = "ARRIVED",
failed = "FAILED",
}
Is it better to use a switch case in the script
tag
<script>
let statusText = ""
$: switch (status) {
case Status.riding:
statusText = "Riding"
break
case Status.arrived:
statusText = "Arrived"
break
case Status.failed:
statusText = "Failed"
break
}
</script>
<span class="status-text">
{statusText}
</span>
…or to use if
/ else if
logic blocks:
<span class="status-text">
{#if status === Status.riding}
"Riding"
{:else if status === Status.arrived}
"Arrived"
{:else if status === Status.failed}
"Failed"
{/if}
</span>
Any recommendation on what to use? Thanks.
Just use a dictionary:
$: statusText = {
[Status.riding]: "Riding",
[Status.arrived]: "Arrived",
[Status.failed]: "Failed",
}[status];
Though it really does not matter (both markup and reactive expressions update just once when the dependencies have changed), and as soon as you need more than a string for content, you will have to use {#if}
/{:else if}
anyway.