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

如何在Vue-i18n中全局配置插值参数统一传递非断字连字符?

问题描述

我正在使用vue-i18n的插值语法在翻译内容中渲染非断行连字符(HTML代码:‑),当前实现方式如下:

组件代码:

{{ $t('message', {char: '‑'}) }}

en.json翻译文件:

"message": "I am working full{char}time on this project."

我希望项目中所有翻译都能自动用上这个非断行连字符,不用每次调用$t都手动传char参数。能不能在i18n配置里全局设置char = ‑,让它自动传入所有翻译?

以下是我的i18n.js配置文件:

import {createI18n} from 'vue-i18n';

function loadLocaleMessages() {
    const pathsGlob = import.meta.glob('../../lang/*.json')
    const messages = {}
    for (const path in pathsGlob) {
        pathsGlob[path]().then((mod) => {
            const locale = path.split('/')[path.split('/').length - 1].split('.')[0]
            messages[locale] = mod
        })
    }
    return messages
}

export default new createI18n({
    locale: navigator.language.substring(0, 2),
    fallbackLocale: 'en',
    messages: loadLocaleMessages(),
    silentTranslationWarn: true,
    silentFallbackWarn: true,
});

解决方案

可以通过扩展$t方法的方式,全局注入默认插值参数,无需每次手动传递。

具体实现

修改你的i18n.js配置文件,包装原生的$t方法,自动合并全局默认参数:

import {createI18n} from 'vue-i18n';

function loadLocaleMessages() {
    const pathsGlob = import.meta.glob('../../lang/*.json')
    const messages = {}
    for (const path in pathsGlob) {
        pathsGlob[path]().then((mod) => {
            const locale = path.split('/')[path.split('/').length - 1].split('.')[0]
            messages[locale] = mod.default // 修正:import.meta.glob导入的JSON需取default导出
        })
    }
    return messages
}

const i18n = createI18n({
    locale: navigator.language.substring(0, 2),
    fallbackLocale: 'en',
    messages: loadLocaleMessages(),
    silentTranslationWarn: true,
    silentFallbackWarn: true,
    globalInjection: true // 确保$t方法全局可用
});

// 包装原生$t方法,自动添加全局参数
const originalTranslate = i18n.global.t;
i18n.global.t = function (key, ...args) {
    // 全局默认插值参数
    const globalParams = { char: '‑' };
    
    // 合并用户传入的参数(用户参数优先级更高)
    if (args.length > 0 && typeof args[0] === 'object') {
        args[0] = { ...globalParams, ...args[0] };
    } else {
        args.unshift(globalParams);
    }
    
    return originalTranslate.call(this, key, ...args);
};

export default i18n;

使用方式

修改完成后,组件中直接调用$t即可自动注入char参数:

{{ $t('message') }}

如果某个翻译需要覆盖全局的char值,直接传入自定义参数即可,会自动覆盖全局默认值:

{{ $t('message', {char: '-'}) }}

内容的提问来源于stack exchange,提问作者Artur Müller Romanov

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.19 00:45:40