当前位置:首页 > VUE

vue3多语言实现

2026-02-09 21:52:15VUE

vue3 多语言实现方案

使用 vue-i18n 插件

安装 vue-i18n 依赖包:

npm install vue-i18n@9

创建语言资源文件(如 locales/en.jsonlocales/zh.json):

{
  "message": {
    "hello": "Hello world!",
    "welcome": "Welcome to Vue 3"
  }
}

初始化 i18n 实例并挂载到 Vue 应用:

import { createI18n } from 'vue-i18n'
import en from './locales/en.json'
import zh from './locales/zh.json'

const i18n = createI18n({
  locale: 'en', // 默认语言
  fallbackLocale: 'en', // 回退语言
  messages: {
    en,
    zh
  }
})

const app = createApp(App)
app.use(i18n)
app.mount('#app')

在组件中使用多语言

模板中使用 $t 方法:

<p>{{ $t('message.hello') }}</p>

脚本中使用:

import { useI18n } from 'vue-i18n'

export default {
  setup() {
    const { t } = useI18n()
    console.log(t('message.welcome'))
  }
}

切换语言功能

添加语言切换按钮:

vue3多语言实现

<button @click="changeLanguage('en')">English</button>
<button @click="changeLanguage('zh')">中文</button>

实现切换方法:

import { useI18n } from 'vue-i18n'

export default {
  setup() {
    const { locale } = useI18n()

    const changeLanguage = (lang) => {
      locale.value = lang
    }

    return { changeLanguage }
  }
}

动态加载语言包

对于大型项目,可以按需加载语言包:

const loadLocaleMessages = async (locale) => {
  const response = await fetch(`./locales/${locale}.json`)
  return response.json()
}

const i18n = createI18n({
  locale: 'en',
  fallbackLocale: 'en',
  messages: {}
})

// 切换语言时加载
const changeLanguage = async (lang) => {
  if (!i18n.global.availableLocales.includes(lang)) {
    const messages = await loadLocaleMessages(lang)
    i18n.global.setLocaleMessage(lang, messages)
  }
  i18n.global.locale.value = lang
}

处理复数形式和变量插值

语言资源文件中定义复数规则:

vue3多语言实现

{
  "apple": {
    "one": "one apple",
    "other": "{count} apples"
  }
}

模板中使用:

<p>{{ $tc('apple', appleCount) }}</p>

带变量的插值:

{
  "greeting": "Hello, {name}!"
}
<p>{{ $t('greeting', { name: userName }) }}</p>

日期和数字本地化

配置日期时间格式:

const i18n = createI18n({
  datetimeFormats: {
    en: {
      short: {
        year: 'numeric',
        month: 'short',
        day: 'numeric'
      }
    },
    zh: {
      short: {
        year: 'numeric',
        month: 'short',
        day: 'numeric'
      }
    }
  }
})

模板中使用:

<p>{{ $d(new Date(), 'short') }}</p>

标签: 多语言
分享给朋友:

相关文章

php实现多语言切换

php实现多语言切换

实现多语言切换的基本方法 在PHP中实现多语言切换通常涉及以下核心步骤:准备语言文件、设置语言标识、动态加载对应语言内容。以下是具体实现方式: 语言文件存储结构 采用键值对方式存储翻译内容,每个语言…

vue实现多语言

vue实现多语言

Vue 实现多语言方案 使用 vue-i18n 插件 安装 vue-i18n 依赖: npm install vue-i18n 在项目中创建语言资源文件,例如: // src/locales/…

php实现多语言切换

php实现多语言切换

PHP 实现多语言切换的方法 使用数组存储多语言文本 创建一个语言文件数组,存储不同语言的文本。例如,创建 lang.php 文件,定义不同语言的键值对: $lang = [ 'en' =&…