vue项目如何实现国际化?分享一下基于vue-i18n实现国际化的经验
demo源码链接:/XieTongXue/how-to/tree/master/vue-internationalization
步骤一:安装vue-i18n
npm install vue-i18n --save
步骤二:main.js文件的配置,在main.js中添加以下跟vue-i18n的使用有关的配置项
// 引入i18n国际化插件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')}})//将i18n注入到vue实例中new Vue({el: '#app',router,store,i18n,components: { App },template: '<App/>'})
两个语言文件(zh.json,en.json)源码如下:
en.json:
{"common": {"home": "Home","login": "Login","register": "Register","appDownload": "APP Download","aboutUs": "About Us","faq": "FAQ","contact": "Contact Us","join": "Join Us","copyright": "Copyright © ZLGMcu Ltd","news": "News","toggle": "Toggle","welcome": "Welcome, ","userinfo": "Userinfo","firstPage": "Home","setting": "Setting","exit": "Exit"},"message": {"hint1": "Please Input Nickname","hint2": "Please Input Username","hint3": "Please Input Password","hint4": "Don't find picture","hint5": "No Account?","hint6": "Register Now","hint7": "Remember me","hint8": "Can't login in?","placeHolder1": "Nickname","placeHolder2": "Username or Phone Number or Email","placeHolder3": "Password(8 Digits at Least)"}}
zh.json:
{"common":{"home": "首页","login": "登录","register": "注册","appDownload": "APP下载","aboutUs": "关于我们","faq": "常见问题","contact": "联系方式","join": "加入我们","copyright": "版权说明 © 广州xxx有限公司","news": "消息","toggle": "切换","welcome": "欢迎您,","userinfo": "个人信息","firstPage": "主页","setting": "设置","exit": "退出"},"message":{"hint1": "请输入昵称","hint2": "请输入账号","hint3": "请输入密码","hint4": "没有找到","hin5": "没有账号?","hint6": "马上注册","hint7": "记住我","hint8": "登录遇到问题?","placeHolder1": "昵称","placeHolder2": "用户名、手机号或邮箱","placeHolder3": "密码(至少8位字符)"}}
步骤三:使用vue-i18n,请只留意划线或框框部分
代码中的common.welcome对应语言文件中对应的项,各个不同的项引用方式一样,因此不全部展示,点击切换语言触发changeLanguage()方法,改变i18n实例中locale的值,进而实现语言的切换。此文章只展示了英文中文两种语言,其实多语言也一样,只要多写几个语言文件,然后在main.js中进行对应的配置就行。
由于main.js中设置了默认显示zh即中文,所以没有点击切换语言按钮前的效果为:
点击切换语言后的效果为:
假如在js中需要国际化,可写成以下形式,举个data中的值国际化的例子:
computed: {type () {return this.$t('xxx.xxx.xxx')}}或者: data () {return {msg: '默认文字'}}methods: {changeLanguage () {// 同上,以下多加一行this.msg = this.$t('xxx.xxx.xxx')}}
demo:/XieTongXue/how-to/tree/master/vue-internationalization
国际化的实现方式有很多,有想到其他方法的欢迎分享;本文的只是其中一种,觉得有不足的地方欢迎指出。