如何在翻译字符串中插入动态变量?
解读
国内项目普遍要求“中英双语”甚至“多语言”,面试官问这一题,并不是考你会不会写 {{ }},而是看你是否:
- 知道 Vue 生态里“官方推荐”的 i18n 方案;
- 能把“静态文案”与“运行时变量”解耦,避免硬编码;
- 理解编译时与运行时的区别,能权衡性能、可维护性与安全;
- 在大型项目中,能处理“名词复数”“货币格式化”“占位符顺序”等真实需求。
一句话:考的是“国际化工程化能力”,不是简单的字符串拼接。
知识点
- Vue I18n 的“列表格式化”与“命名格式化”语法差异;
- 模板内与脚本内两种调用方式:
$t('key', {...})与t('key', {...}); - 动态 key 的写法:
$t(keyRef)与<i18n-t>组件; - 数字、日期、货币与相对时间格式化:Intl.NumberFormat、Intl.DateTimeFormat、Intl.RelativeTimeFormat;
- 复数与性别规则:
pluralizationRules、linked messages; - 性能:编译时预编译 vs 运行时插值;如何避免
v-html带来的 XSS; - 与 Vite/Webpack 集成:
.yaml、.json5、.js资源热更新; - 服务端渲染(SSR)与 hydration 一致性:全局
locale必须在服务端与客户端同步; - 组合式 API:
useI18n()的返回值作用域与<script setup>的编译优化; - 团队协作:文案 key 命名规范、CI 自动提取、翻译平台对接(Crowdin、Phrase)。
答案
- 安装并创建实例
npm i vue-i18n@9
// i18n/index.js
import { createI18n } from 'vue-i18n'
const messages = {
zh: {
welcome: '你好,{name}!今天是 {date},您的积分:{point, number}。'
},
en: {
welcome: 'Hello, {name}! Today is {date}, your points: {point, number}.'
}
}
export default createI18n({
legacy: false, // 使用 Composition API 模式
locale: 'zh',
fallbackLocale: 'en',
messages
})
- 在组件中使用(Composition API)
<template>
<p>{{ $t('welcome', msgParams) }}</p>
<!-- 或者更语义化 -->
<i18n-t keypath="welcome" :params="msgParams" />
</template>
<script setup>
import { reactive } from 'vue'
import { useI18n } from 'vue-i18n'
const { t, locale } = useI18n()
const msgParams = reactive({
name: '王工',
date: new Intl.DateTimeFormat(locale.value).format(new Date()),
point: 12888
})
</script>
- 动态 key 场景
<script setup>
const key = computed(() => `moduleA.${pageType}.title`)
const title = computed(() => t(key.value, { var: 123 }))
</script>
- 安全与性能
- 禁止用
v-html拼接变量,防止 XSS; - 大列表场景用
<i18n-t>组件,避免重复调用$t; - 生产环境开启
runtimeOnly: true,减少打包体积。
拓展思考
-
如果文案来自后端,如何做到“增量热更新”而不刷新页面?
答:通过i18n.global.setLocaleMessage(locale, newMsg)动态注入,同时用import.meta.hot在 Vite 中监听本地.json变更。 -
如何支持“名词性别”与“复数规则”差异巨大的语言(俄语、阿拉伯语)?
答:在pluralizationRules里写自定义函数,返回zero|one|two|few|many|other,并在消息串里用{count, plural, one{...} few{...} other{...}}。 -
微前端场景下,子应用独立部署,如何共享一份语言包?
答:主应用通过importmaps或window.__SHARED_I18N__下发基础包,子应用createI18n时messages: Object.assign({}, base, self),并监听主应用locale变化做i18n.global.locale = newVal。 -
如何防止翻译 key 泛滥、命名冲突?
答:制定“业务域.页面.模块.含义”四级规范,如order.list.table.header.amount;配合 eslint-plugin-vue-i18n 做静态检查;CI 阶段用vue-i18n-extract扫描未使用/缺失 key,自动提工单。 -
服务端渲染时,语言如何与请求头或 Cookie 同步?
答:在entry-server.js里根据req.headers['accept-language']或req.cookies.locale设置i18n.global.locale,并序列化到window.__INITIAL_STATE__,客户端hydrate时恢复,保证同构一致性,避免 hydration mismatch 报错。