You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Svelte中如何让<select>下拉框默认选中对应slug参数值

问题:Svelte页面下拉框绑定deckId后,刷新/导航时选中状态丢失

通过slug参数deckId导航至目标页面,页面内的<select>下拉框已与deckId变量绑定,但导航到页面或刷新页面时,下拉框的选中状态会消失——deckId变量已正确获取到值,却无法在下拉框中显示对应的选中效果。

已尝试的方案

  • 原生DOM操作设置选中值(可解决但方案不优):
deckId = $page.params.deckId;
const selectElement = document.querySelector('select');
selectElement.value = deckId;
  • 给<option>添加selected属性(无效):
<option value={deck.value} selected={deck.value === deckId}>{deck.label}</option>

相关代码

组件脚本部分

import { page } from '$app/stores';
import { goto } from '$app/navigation';
import { Jumper } from 'svelte-loading-spinners';
export let data;
let deckId = $page.params.deckId;
async function handleChangeID(event) {
        goto('/homePage/studyDeck/' + event.target.value + '/' + cardStatus + '/');
        await getCards();
        showBack = false;
    }

模板部分

{#await data.decks}
    <span><Jumper /></span>
{:then decks}
    <h2 class="font-bold mb-2 text-center text-primary-900 my-auto mr-2">Deck</h2>
    <select
        class="border border-gray-300 p-2 w-full h-auto rounded text-primary-900 dark:text-primary-400 bg-background-0 dark:bg-primary-60 mr-4"
        bind:value={deckId}
        on:change={handleChangeID}
    >
        {#each decks as deck}
            <option value={deck.value}>{deck.label}</option>
        {/each}
    </select>
{/await}

+layout.js数据加载部分

export async function load({ fetch }) {
    
    async function getDecks() {
        const API_URL = 'http://localhost:3001/Deck';
        try {
            const response = await fetch(API_URL, {
                method: 'GET',
                headers: {
                    'Content-Type': 'application/json'
                },
                credentials: 'include'
            });
            const data = await response.json();

            return data.map((item) => ({
                value: item.deckId,
                label: item.deckName
            }));
        } catch (error) {
            console.error('Error:', error);
        }
    }

    return {
        decks: getDecks(),
    };
}

求更优的实现方式来解决下拉框选中状态无法同步的问题。

内容的提问来源于stack exchange,提问作者user24162460

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.26 06:33:18