安装uni-i18n插件
npm install uni-i18n
main.js文件中引入并初始化VueI18n
///main.js import messages from './language/index' let i18nConfig = {locale: uni.getLocale(),messages }import Vue from 'vue' import VueI18n from 'vue-i18n' import App from './App' Vue.use(VueI18n) const i18n = new VueI18n(i18nConfig) Vue.config.productionTip = false App.mpType = 'app' const app = new Vue({i18n, ...App }) // 国际化 app.$mount()
建立相关的语言文件夹,存放.js语言文件
定义index.js在设置全局变量
///index.js import en from './enHans.json' import zhHans from './zh-Hans.json' export default {'zh-Hans': zhHans,en, }
在页面中应用
页面模板中使用 t('')
<template><view class="container"><view class="title">{{$t('index.title')}}</view></view> </template
computed: {locales() {return [{text: this.$t('language.zh'),tip:this.$t('language.zh_tip'),code: 'zh-Hans',}, {text: this.$t('language.en'),tip:this.$t('language.en_tip'),code: 'en'}]}},onLoad() {let systemInfo = uni.getSystemInfoSync();this.systemLocale = systemInfo.language;this.applicationLocale = uni.getLocale();uni.onLocaleChange((e) => {this.applicationLocale = e.locale;})},
注:语言API
uni-app内置了一批与国际化相关的API和生命周期。注意要区分系统语言和应用语言的概念。uni.getSystemInfo
可以得到设备OS的语言、运行宿主host的语言以及应用自身的语言。uni.getLocale
获取应用当前使用的语言uni.setLocale
设置应用语言uni.onLocaleChange
当前应用语言发生变化时,触发回调。也就是uni.setLocale执行时。
Vue页面 i18n代码提示
pages.json i18n代码提示