執行如下命令,安裝 i18n 依賴。css
yarn add vue-i18n
$ yarn add vue-i18n yarn add v1.9.4 warning package-lock.json found. Your project contains lock files generated by tools other than Yarn. It is advised not to mix package managers in order to avoid resolution inconsistencies caused by unsynchronized lock files. To clear this warning, remove package-lock.json. [1/5] Validating package.json... [2/5] Resolving packages... [3/5] Fetching packages... info fsevents@1.2.4: The platform "win32" is incompatible with this module. info "fsevents@1.2.4" is an optional dependency and failed compatibility check. Excluding it from installation. [4/5] Linking dependencies... [5/5] Building fresh packages... success Saved lockfile. success Saved 1 new dependency. info Direct dependencies └─ vue-i18n@8.0.0 info All dependencies └─ vue-i18n@8.0.0 Done in 28.19s.
2.1 在 src 下新建 i18n 目錄,並建立一個 index.js。前端
index.jsvue
import Vue from 'vue' import VueI18n from 'vue-i18n' Vue.use(VueI18n) // 註冊i18n實例並引入語言文件,文件格式等下解析 const i18n = new VueI18n({ locale: 'zh', messages: { 'zh': require('@/assets/languages/zh.json'), 'en': require('@/assets/languages/en.json') } }) export default i18n
2.2 在 assets 目錄下面建立連個多語言文件。git
zh.jsonelement-ui
{ "common": { "home": "首頁", "login": "登陸", "exit": "退出" }, "sys": { "userMng": "用戶管理", "deptMng": "機構管理", "roleMng": "角色管理", "menuMng": "菜單管理", "logMng": "日誌管理" } }
en.jsonjson
{ "common": { "home": "Home", "login": "Login", "exit": "Exit" }, "sys": { "userMng": "User Manage", "deptMng": "Dept Manage", "roleMng": "Role Manage", "menuMng": "Menu Manage", "logMng": "Log Manage" } }
2.3 在 main.js 中引入 i18n 並注入到 vue 對象中。後端
import Vue from 'vue' import App from './App' import router from './router' import ElementUI from 'element-ui' import 'element-ui/lib/theme-chalk/index.css' import api from './http/index' import i18n from './i18n' Vue.config.productionTip = false Vue.use(ElementUI) Vue.use(api) new Vue({ el: '#app', i18n, router, render: h => h(App) });
在本來使用字符串的地方,引入國際化字符串。api
把本來的「用戶管理」、「菜單管理」等字符串換成以下格式引入。app
在用戶信息前邊添加一個用於語言切換的菜單,用於切換不一樣的語言。測試
菜單語言切換的時候,修改國際化的設置
選擇點擊切換英文,導航菜單成功切換到英文。
後端:https://gitee.com/liuge1988/kitty
前端:https://gitee.com/liuge1988/kitty-ui.git
做者:朝雨憶輕塵
出處:https://www.cnblogs.com/xifengxiaoma/ 版權全部,歡迎轉載,轉載請註明原文做者及出處。