index.js 1.23 KB
Newer Older
lanbaoming's avatar
lanbaoming committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42
import Vue from 'vue'
import VueI18n from './vue-i18n/vue-i18n.common'
// import {getLocale} from '@/util/db'
Vue.use(VueI18n)

const i18n = new VueI18n({
    locale: uni.getStorageSync('locale')|| 'zh-Hans',
    formatFallbackMessages: false,
    fallbackLocale: 'zh-Hans',
    messages: {
        'en': require('./languages/en_US.json'),
        'zh-Hans': require('./languages/zh_CN.json')
    }
})

/*
用法
$l('title')         => titleZh
$l(item, 'title')   => item.titleZh
$l(null, 'title')   => titleZh
$l()                => Zh
*/
Vue.prototype.$l = i18n.l = (object, field = '') => {
    let prefix = i18n.locale.split(/[-_]/g)[0] // 改成正则让他同时支持-和_,否则$l取值可能会异常
    let append = prefix.charAt(0).toUpperCase() + prefix.toLowerCase().substr(1)
    if(typeof object == 'string'){
        return object + append
    }
    // 如果object是null或者字符串则返回字段名
    if(!object) return field + append

    return object[field + append] || object[field]
}
/* Vue.filter('$t', Vue.$i18n)
 */
// 重新console.warn来捕获未翻译的内容
/* console.wareOrig = console.warn
console.warn = (...data) => {
    console.log('warn', typeof data)
    console.wareOrig(data)
} */
export default i18n