使用vue-i18n實現國際化


在 vue 的項目中,我們不需要手寫這么復雜的一些基礎代碼,可以直接使用 vue-i18n 進行實現(注意:vue3 下需要使用 V 9.x 的 i18n)

vue-i18n 的使用可以分為四個部分:

  1. 創建 messages 數據源
  2. 創建 locale 語言變量
  3. 初始化 i18n 實例
  4. 注冊 i18n 實例

  1. 安裝 vue-i18n:
npm install vue-i18n@next
  1. 創建 i18n/index.js 文件
import {
  createI18n
} from 'vue-i18n'
const messages = {
  en: {
    msg: {
      test: 'hello world'
    }
  },
  zh: {
    msg: {
      test: '你好世界'
    }
  }
}

// 創建locale語言變量
const locale = 'en'

// 初始化 i18n 實例
export const i18n = createI18n({
  // 使用 Composition API 模式,則需要將其設置為false
  legacy: false,
  // 全局注入 $t 函數
  globalInjection: true,
  locale,
  messages
})

export default app => {
  app.use(i18n)
}

  1. 在 main.js 中導入
// i18n (PS:導入放到 APP.vue 導入之前,因為后面我們會在 app.vue 中使用國際化內容)
import i18n from '@/i18n'

app.use(i18n)
  1. 在 layout/components/Sidebar/index.vue 中使用 i18n
<h1 class="logo-title" v-if="$store.getters.sidebarOpened">
        {{ $t('msg.test') }}
</h1>
  1. 修改 locale 的值,即可改變展示的內容
<script setup>
// 引入i18n的hook
import { useI18n } from 'vue-i18n'
import { defineProps, computed } from 'vue'
import { useStore } from 'vuex'
import { ElMessage } from 'element-plus'

defineProps({
  effect: {
    type: String,
    default: 'dark',
    validator: function(value) {
      // 這個值必須匹配下列字符串中的一個
      return ['dark', 'light'].indexOf(value) !== -1
    }
  }
})

const store = useStore()
const language = computed(() => store.getters.language)

// 獲取全局的i18n
const i18n = useI18n()
// 切換語言
const handleSetLanguage = lang => {
  i18n.locale.value = lang
  store.commit('app/setLanguage', lang)
  ElMessage.success('更新成功')
}
</script>
  1. 使用Element-Plus完成進行國際化處理
    對@/plugins/element.js進行語言包選擇設置:
import ElementPlus from 'element-plus'
import 'element-plus/lib/theme-chalk/index.css'
// 引入中文
import zhCn from 'element-plus/lib/locale/lang/zh-cn'
// 引入英文
import en from 'element-plus/lib/locale/lang/en'
import store from '@/store'

export default (app) => {
// 根據當前store設置好的語言,切換Element-Plus組件的中英文
  app.use(ElementPlus, {
    locale: store.getters.language === 'en' ? en : zhCn
  })
}

在i18n/index.js下完成Element-Plus組件的國際化處理

import enLocale from 'element-plus/lib/locale/lang/en'
import zhLocale from 'element-plus/lib/locale/lang/zh-cn'

const messages = {
  en: {
    el: enLocale.el
  },
  zh: {
    el: zhLocale.el
  }
}

const locale = 'en'

export const i18n = createI18n({
  // 使用 Composition API 模式,則需要將其設置為false
  legacy: false,
  // 全局注入 $t 函數
  globalInjection: true,
  locale,
  messages
})

export default app => {
  app.use(i18n)
}

做到這里,按理說,Element-Plus已經可以根據我們的選擇切換中英文了,但是現階段Element-Plus還未完成vue-i18n進行聯動的相關處理,所以需要我們自定義處理。

  1. 自定義語言包國際化處理
    將自定義語言包導入@/i18n目錄下:
    其中,一個為中文語言包zh.js,一個為英文語言包en.js,
    zh.js:
export default {
  login: {
    title: '用戶登錄',
    loginBtn: '登錄',
    usernameRule: '用戶名為必填項',
    passwordRule: '密碼不能少於6位',
    desc: `
    測試權限賬號:<br />
    提供三種權限賬號:<br />
    1. 超級管理員賬號: super-admin <br />
    2. 管理員賬號:admin <br />
    3. 測試可配置賬號:test <br />
    密碼統一為:123456 <br />
    <br />
    導入用戶賬號:<br />
    可使用導入的用戶名登錄 <br />
    密碼統一為:123456  <br />
    <b>注意:導入用戶區分中英文庫!!!!</b>
    `
  },
  route: {
    profile: '個人中心',
    user: '用戶',
    excelImport: 'Excel導入',
    userManage: '員工管理',
    userInfo: '員工信息',
    roleList: '角色列表',
    permissionList: '權限列表',
    article: '文章',
    articleRanking: '文章排名',
    articleCreate: '創建文章',
    articleDetail: '文章詳情',
    articleEditor: '文章編輯'
  },
  toast: {
    switchLangSuccess: '切換語言成功'
  },
  tagsView: {
    refresh: '刷新',
    closeRight: '關閉右側',
    closeOther: '關閉其他'
  },
  theme: {
    themeColorChange: '主題色更換',
    themeChange: '主題更換'
  },
  universal: {
    confirm: '確定',
    cancel: '取消'
  },
  navBar: {
    themeChange: '主題修改',
    headerSearch: '頁面搜索',
    screenfull: '全屏替換',
    lang: '國際化',
    guide: '功能引導',
    home: '首頁',
    course: '課程主頁',
    logout: '退出登錄'
  },
  guide: {
    close: '關閉',
    next: '下一個',
    prev: '上一個',
    guideTitle: '引導',
    guideDesc: '打開引導功能',
    hamburgerTitle: '漢堡按鈕',
    hamburgerDesc: '打開和關閉左側菜單',
    breadcrumbTitle: '面包屑',
    breadcrumbDesc: '指示當前頁面位置',
    searchTitle: '搜索',
    searchDesc: '頁面鏈接搜索',
    fullTitle: '全屏',
    fullDesc: '頁面顯示切換',
    themeTitle: '主題',
    themeDesc: '更換項目主題',
    langTitle: '國際化',
    langDesc: '語言切換',
    tagTitle: '標簽',
    tagDesc: '已打開頁面標簽',
    sidebarTitle: '菜單',
    sidebarDesc: '項目功能菜單'
  },
  profile: {
    muted: '《vue3 改寫 vue-element-admin,實現后台前端綜合解決方案》項目演示',
    introduce: '介紹',
    projectIntroduction: '項目介紹',
    projectFunction: '項目功能',
    feature: '功能',
    chapter: '章節',
    author: '作者',
    name: 'Sunday',
    job: '一個前端開發程序猿',
    Introduction:
      '高級技術專家,曾就職於國內一線互聯網公司,統籌過的多個大型項目用戶數已過千萬級。致力於研究大前端技術,多次受邀參加國內前端技術分享會,如:2018 年 Google 中國技術分享會。'
  },
  userInfo: {
    print: '打印',
    title: '員工信息',
    name: '姓名',
    sex: '性別',
    nation: '民族',
    mobile: '手機號',
    province: '居住地',
    date: '入職時間',
    remark: '備注',
    address: '聯系地址',
    experience: '經歷',
    major: '專業',
    glory: '榮耀',
    foot: '簽字:___________日期:___________'
  },
  uploadExcel: {
    upload: '點擊上傳',
    drop: '將文件拖到此處'
  },
  excel: {
    importExcel: 'excel 導入',
    exportExcel: 'excel 導出',
    exportZip: 'zip 導出',
    name: '姓名',
    mobile: '聯系方式',
    avatar: '頭像',
    role: '角色',
    openTime: '開通時間',
    action: '操作',
    show: '查看',
    showRole: '角色',
    defaultRole: '員工',
    remove: '刪除',
    removeSuccess: '刪除成功',
    title: '導出為 excel',
    placeholder: 'excel 文件名稱',
    defaultName: '員工管理表',
    close: '取 消',
    confirm: '導 出',
    importSuccess: ' 條員工數據導入成功',
    dialogTitle1: '確定要刪除用戶 ',
    dialogTitle2: ' 嗎?',
    roleDialogTitle: '配置角色'
  },
  role: {
    buttonTxt: '新增角色',
    index: '序號',
    name: '名稱',
    desc: '描述',
    action: '操作',
    assignPermissions: '分配權限',
    removeRole: '刪除角色',
    dialogTitle: '新增角色',
    dialogRole: '角色名稱',
    dialogDesc: '角色描述',
    updateRoleSuccess: '用戶角色更新成功'
  },
  permission: {
    name: '權限名稱',
    mark: '權限標識',
    desc: '權限描述'
  },
  article: {
    ranking: '排名',
    title: '標題',
    author: '作者',
    publicDate: '發布時間',
    desc: '內容簡介',
    action: '操作',
    dynamicTitle: '動態展示',
    show: '查看',
    remove: '刪除',
    edit: '編輯',
    dialogTitle1: '確定要刪除文章 ',
    dialogTitle2: ' 嗎?',
    removeSuccess: '文章刪除成功',
    titlePlaceholder: '請輸入文章標題',
    markdown: 'markdown',
    richText: '富文本',
    commit: '提交',
    createSuccess: '文章創建成功',
    editorSuccess: '文章修改成功',
    sortSuccess: '文章排名修改成功'
  }
}

en.js

...

在@/i18n/index.js中完成自定義語言包國際化處理:

import {
  createI18n
} from 'vue-i18n'
import enLocale from 'element-plus/lib/locale/lang/en'
import zhLocale from 'element-plus/lib/locale/lang/zh-cn'
// 引入自定義語言包
import mZhLocale from './lang/zh'
import mEnLocale from './lang/en'
const messages = {
  en: {
    el: enLocale.el,
    msg: {
      ...mEnLocale
    }
  },
  zh: {
    el: zhLocale.el,
    msg: {
      ...mZhLocale
    }
  }
}

const locale = 'en'

export const i18n = createI18n({
  // 使用 Composition API 模式,則需要將其設置為false
  legacy: false,
  // 全局注入 $t 函數
  globalInjection: true,
  locale,
  messages
})

export default app => {
  app.use(i18n)
}

同理,如果需要別的語言包,也可以按這種方式自定義

  1. 處理項目國際化內容

在組件標簽中使用$t()進行處理:

// 在組件中需要中英文切換,不能寫死的地方通過i18n提供的$t()獲取i18n提供的中英文完成內容的替換,如下:
<span>{{ $t('msg.test') }}</span>

在.vue的script中進行處理:

// 引入i18n的鈎子函數
import { useI18n } from 'vue-i18n'
// 獲取i18n全局實例
const i18n = useI18n()
// 使用全局實例調用t()處理
ElMessage.success(i18n.t('msg.toast.swithLangSuccess'))

在.js中進行處理:

import i18n from '@/i18n'
export const validatePassword = () => {
  return (rule, value, callback) => {
    if (value.length < 6) {
      callback(new Error(i18n.global.t('msg.login.passwordRule')))
    } else {
      callback()
    }
  }
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM