Vue实现国际化多语言开发

Vue是现如今比较流行的前端开发框架,具体怎么使用本文就不多介绍了,现在主要分享下自己在开发中所用到的国际化多语言开发,环境使用vue2.0,vue-i18n,vue-resource。

引入必要插件

import Vue from 'vue'
import VueI18n from 'vue-i18n'
import VueResource from 'vue-resource'
Vue.use(VueResource);
Vue.use(VueI18n);

JSON语言包

//中文JSON zh-cn.json
{
    "userName":"用户名",
    "password":"密码",
    "login":"登录",
    "nav":{
        "home":"首页",
        "news":"资讯中心",
        "products":"产品中心",
        "about":"关于我们"
    },
    "week":["星期日","星期一","星期二","星期三","星期四","星期五","星期六"]
}
//英文JSON en-us.json
{
    "userName":"UserName",
    "password":"Password",
    "login":"Login In",
    "nav":{
        "home":"Home",
        "news":"News",
        "products":"Products",
        "about":"About Us"
    },
    "week":["Sun","Mon","Tues","Wed","Thur","Fri","Sat"]
}

语言包引用

let lang='zh-cn';
this.$http.get('/lang/' + lang+'.json').then(function(res){
    if (Object.keys(res.data).length === 0) {
        console.log('Language Package Error!!')
    } else {
        Vue.locale(lang,res.data)
    }
}).then(function(err){
    console.log('Server Connect Error!!');
})

HTML使用

<label>{{$t('userName')}}:<input type="text" />label>
<label>{{$t('password')}}:<input type="password" />label>
<input type="button" :value="$t('login')" />

<ul>
    <li>{{$t('nav.home')}}li>
    <li>{{$t('nav.news')}}li>
    <li>{{$t('nav.products')}}li>
    <li>{{$t('nav.about')}}li>
ul>

<table>
    <tbody>
        <tr>
            <th v-for="n in 6">{{$t('week['+n+']')}}th>
        tr>
        <tr>
            ……
        tr>
    tbody>
table>

更多vue-i18n用法可浏览官网:https://kazupon.github.io/vue-i18n/

你可能感兴趣的:(vue)