vue项目使用vue-i18n实现国际化多语言(ts/js中使用)

633 阅读2分钟

在目前前后端分离的开发模式下,有产品需要实现国际化多语言,使用vue-i18n是非常有必要的。

1.安装vue-i18n i18n在vue中的使用有版本要求,vue2项目一般使用在8这个版本,vue3就要在9版本及以上了 ,以下是安装依赖的命令

pnpm add vue-i18n@9 --save

2.在src文件夹下创建i18n的文件,i18n文件夹下的lang文件中存放的是具体的语言文件

image.png

3.在main.ts中引入

import { i18n } from './i18n/index'
app.use(i18n)

4.在i18n的lang文件夹下新建zh-CN.ts,en.ts这两个文件分别是中文配置和英文配置

zh-CN.ts
export default {
  router: {
    home: '首页',
    setting: '设置',
  }
}
en.ts
export default {
  router: {
    home: 'Home',
    setting: 'Setting',
  }
}

5.在i18n的index.ts文件中写入以下内容

import { createI18n } from 'vue-i18n'
// 框架 国际化文件
const zh_cn = import.meta.glob('./lang/**/zh-CN.ts', { eager: true })
const en = import.meta.glob('./lang/**/en.ts', { eager: true })

// 加载 lang文件夹下的国际化
export const loadLang = (modules: Record<string, any>) => {
  const message: { [key: string]: string } = {}

  Object.keys(modules).forEach((module) => {
    Object.assign(message, { ...modules[module].default })
  })
  return message
}
export const messages: { [key: string]: any } = {
  'zh-CN': {
    langName: '简体中文',
    ...loadLang(zh_cn)
  },
  en: {
    langName: 'English',
    ...loadLang(en)
  }
}

// 返回当前language
function getLanguage() {
  // 默认语言为英文
  return localStorage.getItem('lang') || 'en'
}

export const i18n = createI18n({
  locale: getLanguage(),
  // 需要使用组合式api需要设置
  legacy: false,
  messages
})

6.具体使用

切换语言组件

<template>
    <div v-for="(item, index) in multiLanguage"
         :key="index"
         @click="switchLanguage(item)"
    >
     <label class="flex items-center justify-between cursor-pointer rounded-md   p-2 hover:bg-secondery">
       <span> {{ messages[item].langName }}</span>
       <input type="radio" name="radio-date" checked value="1" />
     </label>
    </div>
</template>

<script lang="ts" setup>
import { messages } from '@/i18n'
import { useI18n } from 'vue-i18n'
import { langStore } from '@/stores'

const multiLanguage = Object.keys(messages)
const { locale } = useI18n()

// 切换语言
const switchLanguage = (language: string) => {
  langStore().setLanguage(language)
  locale.value = language
}
</script>
src/store/modules/lang.ts
import { defineStore } from 'pinia'

export const langStore = defineStore('lang', {
  state: () => ({
    // 国际化多语言
    language: localStorage.getItem('lang') || 'en'
  }),
  actions: {
    setLanguage(local: string) {
      console.log(local)
      // this.language = local
      localStorage.setItem('lang', local)
    }
  }
})

7.第一种方法:在js/ts中使用

import { i18n } from '@/i18n'
 limit_words.value = i18n.global.t('router.home')

8.第二种方法:在js/ts中使用

import { useI18n } from 'vue-i18n'
const { t } = useI18n()
console.log(t('router.home.routerName'))