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

SvelteKit中如何在onMount()内重新赋值变量?

问题原因及解决办法

你的问题核心在于代码执行顺序:

  • onMount 是Svelte的生命周期钩子,它的回调函数会在组件挂载到DOM之后才执行,属于异步触发的时机。
  • 你写在 onMount(showEventIndicator) 后面的 console.log(selectedDate) 是同步代码,会在组件初始化阶段直接执行——这时候 showEventIndicator 还没运行,selectedDate 自然还是初始的 undefined。

具体解决方式

1. 把打印逻辑放到赋值完成后

直接在 showEventIndicator 内部赋值后打印,就能拿到正确的值:

import { onMount } from 'svelte';

let selectedDate;

function showEventIndicator(){
    const containerIndicator = dateContainer.querySelectorAll('.event-indicator');

    containerIndicator.forEach((element: Element, index: number )=> {
        if (element.parentNode instanceof Element && element.parentNode.getAttribute('aria-selected') === 'true'){
            selectedDate = element.parentNode.getAttribute('data-value');
            console.log(selectedDate); // 这里能输出正确的日期值
        }
    });
}

onMount(showEventIndicator);

2. 用Svelte响应式特性监听变量变化

如果需要在组件其他逻辑中使用 selectedDate,可以用Svelte的响应式声明($:),它会在依赖变量变化时自动执行代码:

import { onMount } from 'svelte';

let selectedDate;

function showEventIndicator(){
    const containerIndicator = dateContainer.querySelectorAll('.event-indicator');

    containerIndicator.forEach((element: Element, index: number )=> {
        if (element.parentNode instanceof Element && element.parentNode.getAttribute('aria-selected') === 'true'){
            selectedDate = element.parentNode.getAttribute('data-value');
        }
    });
}

onMount(showEventIndicator);

// 当selectedDate被赋值后,自动执行这里的逻辑
$: if (selectedDate) {
    console.log(selectedDate);
    // 其他需要用到selectedDate的业务逻辑也可以放在这里
}

额外提醒

如果页面中没有符合 aria-selected="true" 条件的元素,selectedDate 仍会是 undefined,建议在后续逻辑中添加判断,避免意外错误。

内容的提问来源于stack exchange,提问作者User-Suuro

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.27 21:32:35