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

如何修复JS文件中Vue i18n切换语言后动态翻译不生效的问题

问题原因

你的menu对象的name属性是脚本初始化时一次性执行i18n.t('Strona główna')得到的静态值,后续切换语言时不会重新触发翻译逻辑,因此不会自动更新。

修复方案

分两种常见场景处理:

场景1:menu定义在Vue组件内部

不要将翻译结果写死在data等非响应式计算的字段中,改为放在computed计算属性中,依赖i18n的响应式能力自动更新:

// 选项式API写法
export default {
  computed: {
    menu() {
      return {
        name: this.$t('Strona główna')
      }
    }
  }
}

// Composition API写法
import { computed } from 'vue'
import { useI18n } from 'vue-i18n'

export default {
  setup() {
    const { t } = useI18n()
    const menu = computed(() => ({
      name: t('Strona główna')
    }))
    return { menu }
  }
}

场景2:menu是组件外的公共配置

方案A:改为函数形式调用

将menu定义为返回配置对象的函数,每次使用时调用即可拿到最新翻译结果:

// 定义处
export const getMenu = () => ({
  name: i18n.t('Strona główna')
})

// 业务代码使用处
const menu = getMenu()

方案B:绑定响应式更新

如果需要menu本身是响应式的,可以借助Vue的响应式能力监听语言切换自动更新:

// Vue2 写法
import Vue from 'vue'
export const menu = Vue.observable({
  name: i18n.t('Strona główna')
})
// 监听语言切换更新翻译
i18n.watch(() => i18n.locale, () => {
  menu.name = i18n.t('Strona główna')
})

// Vue3 写法
import { reactive, watch } from 'vue'
export const menu = reactive({
  name: i18n.t('Strona główna')
})
watch(() => i18n.locale, () => {
  menu.name = i18n.t('Strona główna')
})
注意事项

切换语言时必须直接修改i18n实例的locale属性,不要仅修改初始化时传入的外部language变量,否则无法触发i18n的更新逻辑:

// 正确写法
i18n.locale = 'en'

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.22 00:15:03