# 国际化

uView Next 新增了国际化支持,基于 Vue I18n 实现,默认使用中文语言,内置8种语言切换

# 基础用法

# 1. 安装和配置

main.js 中引入并配置国际化:

main.js
import App from './App';
import zhCN from './locale/zh-CN.json';
import enUS from './locale/en-US.json';
import uView, { VueI18n, createI18n } from '@/uni_modules/uview-next';

// #ifndef VUE3
Vue.use(VueI18n)  //vue3不需要
// #endif

const i18n = createI18n({
	locale: 'zh-CN', // 默认显示语言
	fallbackLocale: 'en-US', // 回退语言
	messages: {
		'zh-CN': zhCN,
		'en-US': enUS
	}
})

// #ifndef VUE3
import Vue from 'vue';
Vue.config.productionTip = false;

Vue.use(uView);

App.mpType = 'app';
const app = new Vue({
	i18n,
	...App
});
app.$mount();
// #endif

// #ifdef VUE3
import { createSSRApp } from 'vue';
export function createApp() {
	const app = createSSRApp(App);

	app.use(uView);
	app.use(i18n);
	
	return {
		app
	};
}
// #endif
✅ Copy success!

# 2. 语言包配置

创建语言包文件,例如 locale/zh-CN.json

locale/zh-CN.json
{
	"index.desc": "uView Next,基于2.0.38支持vue2和vue3,全面兼容nvue的uni-app生态框架,全面的组件和便捷的工具会让您信手拈来,如鱼得水。"
}
✅ Copy success!
locale/en-US.json
{
	"index.desc": "uView Next, Based on 2.0.38 support for Vue2 and Vue3, fully compatible with nvue's uni app ecosystem framework, comprehensive components and convenient tools will make you feel at ease."
}
✅ Copy success!

# 3. 在页面模板和js中使用

页面模板中使用 $t() 获取,并传递国际化json文件中定义的key,js中使用 this.$t('')

<template>
  <view class="container">
    <view class="desc">{{$t('index.desc')}}</view>
  </view>
</template>

<script>
  export default {
    data() {
      return {
      }
    }
  }
</script>
✅ Copy success!

# 4. 切换语言

<script>
const changeLanguage = () => {
    uni.$u.setLocale('en-US')
}
</script>
✅ Copy success!

注意

vue-i18n.esm-bundler.js:33 You are running the esm-bundler build of vue-i18n. It is recommended to configure your bundler to explicitly replace feature flag globals with boolean literals to get proper tree-shaking in the final bundle.

关于控制台显示上面的警告,是由于 vue-i18n 9.1.9版本的内部代码引起的,只要是非生产环境就会有此问题,不影响功能的正常使用。 如果确实看着难受,想删除,可使用下面的办法:

直接找到文件下面的文件

HBuilderX的安装路径/plugins/uniapp-cli-vite/node_modules/vue-i18n/dist/vue-i18n.esm-bundler.js

找到第43行代码,把 needWarn = true; 改成 needWarn = false;或者 console.warn 注释即可

参考链接: https://ask.dcloud.net.cn/question/156161 (opens new window) https://ask.dcloud.net.cn/question/195458 (opens new window)

# 配置说明

# createI18n 参数

参数 类型 默认值 说明
locale String 'zh-CN' 当前语言
fallbackLocale String 'en-US' 回退语言,当当前语言包中找不到对应翻译时使用
messages Object {} 语言包对象

# 组件支持的语言

  • zh-CN: 简体中文
  • zh-HK: 繁体中文(香港)
  • en-US: 英文
  • ja-JP: 日文
  • ko-KR: 韩文
  • fr-FR: 法文
  • de-DE: 德文
  • es-ES: 西班牙文
  • ru-RU: 俄文
  • ar-SA: 阿拉伯文
新版发布
uView Next 4.0重磅发布,支持uniapp、uniapp x、鸿蒙、小程序、全端兼容的UI框架
×