You need to enable JavaScript to run this app. Vue3配合vue-cli-plugin-i18n无法动态切换国际化语言问题求助
优惠活动
大模型
产品
解决方案
定价
更多

Vue3配合vue-cli-plugin-i18n无法动态切换国际化语言问题求助

问题原因

你使用的是vue-i18n v9的Composition API模式(配置项legacy: false即代表开启该模式),该模式下全局locale的修改规则和legacy模式完全不同:

  1. 全局语言配置不再直接挂载在i18n.locale下,而是挂载到i18n.global.locale属性上
  2. 该属性是ref类型的响应式对象,直接赋值不会触发响应式更新,必须修改其value属性才会生效

解决方案

修改main.js中路由守卫的赋值逻辑即可:

router.beforeEach((to, from, next) => {
    let language = to.params.lang;
    if (!language) {
        language = 'en'
    }
    // 替换原有 i18n.locale = language 为以下代码
    i18n.global.locale.value = language
    console.log("Active locale: ", i18n.global.locale.value)
    next()
})

补充说明

如果是在组件内使用Composition API切换语言,通过useI18n()获取到的locale也是ref类型,修改时同样需要加.value:

import { useI18n } from 'vue-i18n'
const { locale } = useI18n()
// 切换语言
locale.value = 'en'

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.15 23:54:01