前端攻城狮

uni-app 语言化 Vue-i18n

2019-05-06  本文已影响807人  前端小慵卿
说到vue-i18n,我们并不陌生,国际化多语言实现。

1.安装依赖包

//vue-i18n
npm install vue-i18n
//除了安装依赖包以外,还可以直接<script>标签直接引入,这种方式自行百度

2.注入vue实例中,项目中实现调用api和模板语法

(1)在main.js中引入vue-i18n

import Vue from 'vue'
import App from './App'
import store from './store'
import VueI18n from 'vue-i18n' 

Vue.use(VueI18n)
Vue.config.productionTip = false
Vue.prototype.$store = store

const i18n = new VueI18n({
    locale : 'en-US', //语言标识
    messages: {
        'en-US' : require('common/lang/en.js') , //英文语言包
        'zh-CN' : require('common/lang/zh.js')  //中文繁体语言包
    }
})

Vue.prototype._i18n = i18n

Vue.prototype.$i18nMsg = function(e){//方便调用js文件而写
    if(e){
        console.log(i18n.messages[i18n.locale].index.e); //undefined
        //用key键值对的方式去写
        console.log(i18n.messages[i18n.locale].index[e]);
        return i18n.messages[i18n.locale].index[e]
    }
    return ' ' //防止没有数据时,占位使用
}
App.mpType = 'app'

const app = new Vue({
    i18n,//重要!!!!
    store,
    ...App
})
app.$mount()

(2)en.js与zh.js

//语言包
export const index = {
    //英文语言包
    "statistics":'Statistics',
    "message":'Message',
        ......
}

(3)页面渲染

//普通渲染,v-for
{{ $i18nMsg(i.text) }}
//还有其他情况,之后补充。

上一篇 下一篇

猜你喜欢

热点阅读