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

从vue-i18n迁移到nuxt-i18n时如何正确结合Vuex使用?

nuxt-i18n 与 Vuex 协作逻辑及迁移改造方案

一、nuxt-i18n 内置 Vuex 模块的工作逻辑

你在配置中开启了vuex相关配置后,nuxt-i18n 会自动在 Vuex 中注册名为nuxt-i18n的独立模块,核心规则如下:

  • 你配置的syncLocale: true生效时,模块会自动将当前激活的 locale 同步到自身 state 中,$i18n.setLocale调用后会自动更新该状态,不需要手动维护
  • 模块内置的 state 已经包含你配置的所有locales数组、当前激活locale等核心状态,不需要在自定义 Store 中重复定义
  • 你原有自定义的i18nStore 和自动生成的nuxt-i18n模块默认无关联,这也是你看到两个独立 Store 模块的原因

二、Store 改造方案

完全不需要合并两个模块,只需要删除自定义 Store 中重复的状态和 mutations,仅保留自定义工具方法,直接引用nuxt-i18n模块的状态即可,改造后的自定义 i18n Store 代码如下:

export const getters = {
  // 直接引用nuxt-i18n内置模块的全量locale配置
  locales: (state, getters, rootState) => rootState['nuxt-i18n'].locales,
  // 直接引用nuxt-i18n自动同步的当前激活locale
  currentLocale: (state, getters, rootState) => rootState['nuxt-i18n'].locale,
  // 以下保留原有自定义工具方法,直接复用上面的getters即可
  locale: (state, getters) => {
    return getters.currentLocale?.iso ? getters.currentLocale : getters.getLocaleFromCode(this.$i18n.defaultLocale)
  },
  language: (state, getters) => {
    return getters.currentLocale?.iso ? getters.currentLocale.iso.split('-')[0] : this.$i18n.defaultLocale
  },
  getLocaleFromCode: (state, getters) => (code) => {
    code = code.split('-')[0]
    return getters.locales.find((locale) => locale.iso === code)
  },
  getLocalesFromLanguage: (state, getters) => (language) => {
    return getters.locales.filter((locale) => locale.iso.split('-')[0] === language)
  }
}

配套业务代码调整

  • 原有调用自定义setLocale mutation 的逻辑全部替换为调用await $i18n.setLocale(目标locale编码),nuxt-i18n 会自动同步状态到 Vuex
  • 原有读取$store.state.i18n.locale的逻辑可以直接替换为读取$i18n.locale,或者自定义 Store 中对应的 getters

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.21 07:15:10