國際化支持
1.安裝依賴
執行以下命令,安裝 i18n 依賴。
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.添加配置
2.1 在 src 下新建 i18n 目錄,並創建一個 index.js。
index.js
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 目錄下面創建連個多語言文件。
zh.json
{ "common": { "home": "首頁", "login": "登錄", "exit": "退出" }, "sys": { "userMng": "用戶管理", "deptMng": "機構管理", "roleMng": "角色管理", "menuMng": "菜單管理", "logMng": "日志管理" } }
en.json
{ "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) });
3.字符引用
在原本使用字符串的地方,引入國際化字符串。
把原本的“用戶管理”、“菜單管理”等字符串換成如下格式引入。
3.切換菜單
在用戶信息前邊添加一個用於語言切換的菜單,用於切換不同的語言。
菜單語言切換的時候,修改國際化的設置
4.啟動測試
選擇點擊切換英文,導航菜單成功切換到英文。
源碼下載
后端:https://gitee.com/liuge1988/kitty
前端:https://gitee.com/liuge1988/kitty-ui.git
作者:朝雨憶輕塵
出處:https://www.cnblogs.com/xifengxiaoma/
版權所有,歡迎轉載,轉載請注明原文作者及出處。