国际化多语言支持是现在系统通常都要具备的功能,Vue对国际化提供了很好的支持。
1. 安装依赖
首先需要安装国际化组件,执行yarn add vue-i18n命令,安装i18n依赖。
2.添加配置
在src下新建i18n目录,并创建一个index.js.
import Vue from ‘vue‘ import VueI18n from ‘vue-i18n‘ Vue.use(VueI18n) // 注册i18n实例并引入语言文件,文件格式等下解析 const i18n = new VueI18n({ locale: ‘zh_cn‘, messages: { ‘zh_cn‘: require(‘@/assets/languages/zh_cn.json‘), ‘en_us‘: require(‘@/assets/languages/en_us.json‘) } }) export default i18n
然后在assets目录下创建两个多语言文件,如图所示:
zh_cn.json:
{ "common": { "home": "首页", "login": "登录", "logout": "退出登录", "doc": "文档", "blog": "博客", "projectRepo": "项目", "myMsg": "我的消息", "config": "系统配置", "backup": "备份", "restore": "还原", "backupRestore": "备份还原", "versionName": "版本名称", "exit": "退出" }, "action": { "operation": "操作", "add": "新增", "edit": "编辑", "delete": "删除", "batchDelete": "批量删除", "search": "查询", "loading": "拼命加载中", "submit": "提交", "comfirm": "确定", "cancel": "取消", "reset": "重置" } }
en_us.json:
{ "common": { "home": "Home", "login": "Login", "logout": "Logout", "doc": "Document", "blog": "Blog", "projectRepo": "Project", "myMsg": "My Message", "config": "Config", "backup": "Backup", "restore": "Restore", "backupRestore": "Backup Restore", "versionName": "Version", "exit": "Exit" }, "action": { "operation": "Operation", "add": "Add", "edit": "Edit", "delete": "Delete", "batchDelete": "Batch Delete", "search": "Search", "loading": "loading", "submit": "Submit", "comfirm": "Comfirm", "cancel": "Cancel", "reset": "Reset" } }
在main.js中引入i18n并注入vue对象中:
import Vue from ‘vue‘ import App from ‘./App‘ import router from ‘./router‘ import api from ‘./http‘ import i18n from ‘./i18n‘ import global from ‘@/utils/global‘ import ElementUI from ‘element-ui‘ import ‘element-ui/lib/theme-chalk/index.css‘ import ‘font-awesome/css/font-awesome.min.css‘ Vue.use(ElementUI) // 注册使用Element Vue.use(api) // 注册使用API模块 Vue.prototype.global = global // 挂载全局配置模块 new Vue({ el: ‘#app‘, i18n, router, render: h => h(App) })
3.字符引用
在原本使用字符串的地方引入国际化字符串。
打开Home.vue,在模板下面添加一个国家化字符串和两个按钮做中英文切换。
<h3>{{$t(‘common.doc‘)}}</h3> <el-button type="success" @click="changeLanguage(‘zh_cn‘)">简体中文</el-button> <el-button type="success" @click="changeLanguage(‘en_us‘)">English</el-button>
在方法声明区域添加以下方法,设置国际化语言:
// 语言切换 changeLanguage(lang) { lang === ‘‘ ? ‘zh_cn‘ : lang this.$i18n.locale = lang this.langVisible = false }
通过this.$i18n.locale = xx方式就可以全局切换语言,Vue框架会根据locale的值读取对应的国际化多语言文件并进行适时更新。
原文地址:https://www.cnblogs.com/xc-xinxue/p/12528041.html
时间: 2024-10-09 01:05:27