前端使用vue-i18n做中英文翻译
vue-i18n 仓库地址:https://github.com/kazupon/vue-i18n
兼容性:
支持 Vue.js 2.x 以上版本
安装方法:(此处只演示 npm)
npm install vue-i18n
使用方法:
1、在 main.js 中引入 vue-i18n (前提是要先引入 vue)
import VueI18n from 'vue-i18n'Vue.use(VueI18n)
2、准备本地的翻译信息
const messages = {zh: {message: {hello: '好好学习,天天向上!'}},en: {message: {hello: 'good good study, day day up!'}} }
3、创建带有选项的 VueI18n 实例
const i18n = new VueI18n({locale: 'en', // 语言标识messages })
4、把 i18n 挂载到 vue 根实例上
const app = new Vue({router,i18n,...App }).$mount('#app')
5、在 HTML 模板中使用
<div id="app"><h1 style="font-size: 16px; text-align: center;">{{ $t("message.hello") }}</h1></div>
查看运行效果:
我们刚才选定的语言标识是 “en” 英语,现在改成 “zh” 中文,并查看效果
const i18n = new VueI18n({locale: 'zh', // 语言标识messages })
这样就可以轻松实现国际化了,实际开发中,页面内容肯定是很多的,我们可以把对应语言的信息保存为不同的 json对象
const i18n = new VueI18n({locale: 'en', // 语言标识messages: {'zh': require('./common/lang/zh'),'en': require('./common/lang/en')} })
zh.js
// 注意:一定是 exports,不是 export,否则会报错,报错信息是下列的中的内容不是 string module.exports = {message: {title: '运动品牌'},placeholder: {enter: '请输入您喜欢的品牌'},brands: {nike: '耐克',adi: '阿迪达斯',nb: '新百伦',ln: '李宁'} }
en.js
module.exports = {message: {title: 'Sport Brands'},placeholder: {enter: 'Please type in your favorite brand'},brands: {nike: 'Nike',adi: 'Adidas',nb: 'New Banlance',ln: 'LI Ning'} }
接下来,在HTML 模板中使用,要特别注意在 js 中的国际化写法
// HTML <div id="app"><div style="margin: 20px;"><h1>{{$t("message.title")}}</h1><input style="width: 300px;" class="form-control" :placeholder="$t('placeholder.enter')"><ul><li v-for="brand in brands">{{brand}}</li></ul></div> </div>// JS data () {return {brands: [this.$t('brands.nike'), this.$t('brands.adi'), this.$t('brands.nb'), this.$t('brands.ln')]}},
查看编译效果:
现在换成英文的:
在上面的操作中,我们都是通过手动修改 locale 的属性值来切换语言,实际上,更希望浏览器自动识别,这里可以借助于 cookie
1、新建一个 cookie.js 文件,用于读取cookie
function getCookie(name,defaultValue) {var arr, reg = new RegExp("(^| )" + name + "=([^;]*)(;|$)");if (arr = document.cookie.match(reg))return unescape(arr[2]);elsereturn defaultValue; }export {getCookie }
2、在 main.js 中引入这个js,并通过 PLAY_LANG 属性来获取浏览器的语言
const i18n = new VueI18n({locale: getCookie('PLAY_LANG','zh'), // 语言标识messages: {'zh': require('./common/lang/zh'),'en': require('./common/lang/en')} })
这里需要注意两个极易出错的地方:
(1)、将 $t() 写成了 $()
(2)、json 中在同一个对象里有同名属性
vue-i18n 提供了一个全局配置参数叫 “locale”,通过改变 locale 的值可以实现不同语种的切换
下面的案例借用了 Element UI 的弹窗样式,上面的步骤不再赘述,直接上核心代码
// template <h2>{{$t('test')}}</h2> <button type="button" class="btn btn-success" @click="changeLocale">中文/EN</button>
// js方法 changeLocale () {this.$confirm(this.$t('layer.toggle'), this.$t('layer.tips'), {confirmButtonText: this.$t('button.ok'),cancelButtonText: this.$t('button.cancel'),type: 'warning'}).then(() => {let locale = this.$i18n.localelocale === 'zh' ? this.$i18n.locale = 'en' : this.$i18n.locale = 'zh'}).catch(() => {this.$message({type: 'info',}) }) },
效果:
在配合 Element-UI 一起使用时,会有2个问题:
(1)、页面刷新后,通过按钮切换的语言还原成了最初的语言,无法保存
(2)、框架内部自带的提示文字无法更改,比如像时间选择框内部中的提示文字
关于第一个问题,可以在初始化VueI18n实例时,通过 localStorage 来为 locale 对象赋值
const i18n = new VueI18n({locale: localStorage.getItem('locale') || 'zh',messages })
在切换语言的时候可以缓存不同的语言选项,并且可以长期保存,不会因为刷新网页而改变locale 的属性值
<div class="lang"><el-dropdown><i class="iconfont icon-language4"></i><el-dropdown-menu slot="dropdown"><el-dropdown-item @click.native="toggleLang('zh')" :disabled="$i18n.locale == 'zh'">中文</el-dropdown-item><el-dropdown-item @click.native="toggleLang('en')" :disabled="$i18n.locale == 'en'">English</el-dropdown-item></el-dropdown-menu></el-dropdown></div>
toggleLang(lang) {if(lang == 'zh'){localStorage.setItem('locale', 'zh')this.$i18n.locale = localStorage.getItem('locale')this.$message({message: '切换为中文!',type: 'success'})} else if (lang == 'en') {localStorage.setItem('locale', 'en')this.$i18n.locale = localStorage.getItem('locale')this.$message({message: 'Switch to English!',type: 'success'}) }
关于第二个问题,更改Element 组件内部语言,这里还涉及到 手动处理 vue-i18n@6.x 兼容性问题。官网已经做了详细介绍,这里依葫芦画瓢跟着实现一下
i18n.jsimport Vue from 'vue' import VueI18n from 'vue-i18n' import locale from 'element-ui/lib/locale'; import zh from './langs/zh' import en from './langs/en' import enLocale from 'element-ui/lib/locale/lang/en' import zhLocale from 'element-ui/lib/locale/lang/zh-CN'Vue.use(VueI18n)const messages = {en: Object.assign(en, enLocale),zh: Object.assign(zh, zhLocale) }console.log(messages.zh)const i18n = new VueI18n({locale: localStorage.getItem('locale') || 'zh',messages })locale.i18n((key, value) => i18n.t(key, value)) //为了实现element插件的多语言切换export default i18n
按照如上把国际化文件都整合到一起,避免main.js 中大段引入相关代码。main.js 中与 i18n 相关的就只剩两行代码
import i18n from './i18n/i18n' // 1行window.app = new Vue({el: '#app',router,store,i18n, // 2行components: { App },template: '<App/>' })
效果如下:
以上demo地址:https://github.com/frwupeng517/element-admin/tree/master/src/i18n
简单配置 参考: https://www.jianshu.com/p/2d3119f9bfd8
转载于:https://www.cnblogs.com/hpx2020/p/9684825.html
前端使用vue-i18n做中英文翻译相关推荐
- vue 后台翻译_前端使用vue-i18n做中英文翻译
vue-i18n 仓库地址:https://github.com/kazupon/vue-i18n 兼容性: 支持 Vue.js 2.x 以上版本 安装方法:(此处只演示 npm) npm insta ...
- vue 使用i18n和i18n Ally自动化翻译
以下为vue2.x使用i18n和i18n Ally自动化翻译的步骤, vue3.x配置步骤>> vue 版本 > 2.6.12 vue-i18n 版本 > 8.25.0 1.安 ...
- 前端学习(1435):vue能做什么
#### 1.3 Vue 能做什么- 最大程度上解放了 DOM 操作 - 单页web项目(SinglePageApplication项目,例如[Worktile官网](https://worktile ...
- vue中开发多语言(国际化),vue+i18n(详细教程)
目录 第一步: 第二步: 第三步: 第四步: 最后: 前言:我们有时候会遇到一个项目需要支持多语言,而用直接翻译的插件时常会导致翻译的结果跟自己预想的有所偏差或者结果太长造成页面结构紊乱而这个时候就需 ...
- 前端面试-Vue系列
目录 有使用过vue吗?说说你对vue的理解 是什么 Vue核心特性 数据驱动(MVVM) 组件化 指令系统 Vue跟传统开发的区别 Vue和React对比 相同点 区别 你对SPA单页面的理解,它的 ...
- vue2项目使用i18n进行中英文切换
vue+element 使用i18n进行中英文切换 文章目录 前言 一.下载vue-i18n插件 二.定义中英文两套js文件,配置i18n,并在main.js中引入 三.通过点击事件切换语言 四.i1 ...
- 前端基于vue企业微信JS-SDK语音识别功能开发(同公众号)
前端基于vue企业微信JS-SDK语音识别功能开发(同公众号) 微信JS-SDK 1.前期准备 前端代码撰写 微信JS-SDK 前端需要实现一个功能,如录音,拍照,分享,地理位置等,前端想要实现这些功 ...
- vue ui框架_你为什么要使用前端框架Vue?
1.前端框架的根本意义 1.1 前端框架的好处 最开始学习前端框架的时候(我第一个框架是 React)并不理解框架能带来什么,只是因为大家都在用框架,最实际的一个用途就是所有企业几乎都在用框架,不用框 ...
- redirect路由配置 vue_Web前端:Vue路由进阶配置
大家好,我来了,本期为大家带来的前端开发知识是"Web前端:Vue路由进阶配置",有兴趣做前端的朋友,和我一起来看看吧! 1. 页面打开权限流程 页面是否能打开有以下两点判断: 1 ...
最新文章
- weblogic在linux服务器上部署应用
- ijkplayer支持h264
- 全排列问题pascal解题程序
- [bootstrapValidator] - bootstrap的验证工具
- boost::sort模块实现带有右移函子排序示例的整数排序的测试程序
- redis删除指定key中的指定元素
- 使用split_size优化的ODPS SQL的场景
- Python 实现网络爬虫小程序
- c语言作业帮,少训练大功课C语言
- C语言控制台窗口图形界面编程(五).
- iOS Dev (60) 怎样实现 UITextView 中的 placeHolder
- python-json操作
- Redis 不安全临时文件漏洞
- 深度置信网络python3实现
- 使用Python将DOTA数据集的格式转换成VOC2007数据集的格式
- BIM标准丨深圳市住房和建设局关于印发《房屋建筑工程招标投标建筑信息模型技术应用标准》
- 域名注册之后如何操作
- 【转载】人工智能发展简史
- 【Android-Kotlin】匿名内部类与Lambda 表达式(附RecycleView监听)
- 第九章 更自由,更开放,大数据的机遇和挑战