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

如何在自定义i18n封装的t函数中获取writable当前值?

解决方案

核心思路是在本地化逻辑内部维护当前语言状态,通过订阅store自动更新该状态,让t函数无需从UI传入参数就能获取当前语言值。

修改本地化逻辑文件

import { writable } from 'svelte/store';

const resources = {
    "en": {
        "hello": "Hello",
    },
    "uk": {
        "hello": "Привіт"
    }
}

export function createLocalization() {
    let currentLocale = "en";
    const store = writable(currentLocale);

    // 订阅store,自动同步当前语言值
    const unsubscribe = store.subscribe(value => {
        currentLocale = value;
    });

    return {
        unsubscribe,
        toggleLocale: () => {
            store.update(prev => prev === "en" ? "uk" : "en");
        },
        t: (key: string): string => {
            // 直接使用内部维护的最新语言值
            return resources[currentLocale]?.[key] ?? key;
        },
        // 可选:暴露语言状态store,方便其他场景监听
        locale: store
    }
}

export const localization = createLocalization();

UI组件代码(无需额外传参)

<script>
  import { localization } from './localization.ts';
</script>

<p>{localization.t("hello")}</p>
<button on:click={localization.toggleLocale}>切换语言</button>

补充说明

  • 通过store.subscribe监听语言变化,自动更新内部的currentLocale,保证t函数始终能拿到最新的语言设置
  • 给t函数添加?? key兜底逻辑,避免找不到对应翻译时显示空白
  • 可选暴露的locale store,可用于其他需要直接监听语言变化的组件场景

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 16:01:11