1、我使用的插件是lime-i18n。

lime-i18n - DCloud 插件市场

2、额看半天才弄懂,记录下来吧。

在项目路径下创建locales文件夹,分别创建en_US.uts、zh-CN.uts、index.uts文件。

en_US.uts代码如下:

export default {
	common: {
		more: "Look More",
		hello: '{msg} world'
	},
	leftMenus: {
		// "/": "Home",
		// Home: "Home",
		home: "Home",
	},
	headMenus: {
		"subTitle": "Organization service platform",
		"userName": "ZhangSan"
	},
	login: {
		"personal_center": "personal center",
		"sign_out": "sign out"
	},
	plurals: {
		car: 'car | cars',
		apple: 'no apples | one apple | {count} apples',
		format: {
			named: 'Hello {name}, how are you? | Hi {name}, you look fine',
			list: 'Hello {0}, how are you? | Hi {0}, you look fine'
		},
		fallback: 'this is fallback | this is a plural fallback'
	},
	message: {
		hello: 'the world',
		helloName: 'Hello {name}',
		hoge: 'hoge',
		link: '@:message.hello',
		linkHelloName: '@:message.helloName',
		linkLinkHelloName: '@:message.linkHelloName',
		linkEnd: 'This is a linked translation to @:message.hello',
		linkWithin: 'Isn\'t @:message.hello we live in great?',
		linkMultiple: 'Hello @:message.hoge!, isn\'t @:message.hello great?',
		linkBrackets: 'Hello @:(message.hoge). Isn\'t @:(message.hello) great?',
		linkHyphen: '@:hyphen-hello',
		linkUnderscore: '@:underscore_hello',
		linkPipe: '@:pipe|hello',
		linkColon: '@:(colon:hello)',
		linkList: '@:message.hello: {0} {1}',
		linkCaseLower: 'Please provide @.lower:message.homeAddress',
		linkCaseUpper: '@.upper:message.homeAddress',
		linkCaseCapitalize: '@.capitalize:message.homeAddress',
		linkCaseUnknown: '@.unknown:message.homeAddress',
		linkCaseCustom: '@.custom:message.homeAddress',
		homeAddress: 'home Address',
		circular1: 'Foo @:message.circular2',
		circular2: 'Bar @:message.circular3',
		circular3: 'Buz @:message.circular1',
		linkTwice: '@:message.hello: @:message.hello',
		the_world: 'the world',
		dio: 'DIO:',
		linked: '@:message.dio @:message.the_world !!!!',
		missingHomeAddress: 'Please provide @.lower:message.homeAddress',
		snake: 'snake case',
		custom_modifier: "custom modifiers example: @.snakeCase:{'message.snake'}"
	},

	address: "{account}{'@'}{domain}",
	'hyphen-hello': 'hyphen the wolrd',
	underscore_hello: 'underscore the wolrd',
	// 'colon:hello': 'hello colon',
	// 'pipe|hello': 'hello pipe',
};

zh-CN.uts代码如下:

export default {
	common: {
		more: "查看更多",
		hello: "{msg} 世界"
	},
	leftMenus: {
		home: "首页"
	},
	headMenus: {
		subTitle: "组织服务平台",
		userName: "张三"
	},
	login: {
		personal_center: "个人中心",
		sign_out: "退出登录"
	},
	plurals: {
		car: '车 | 辆车',
		apple: '没有苹果 | 一个苹果 | {count} 个苹果',
		format: {
			named: '你好 {name},你好吗? | 嗨 {name},你看起来不错',
			list: '你好 {0},你好吗? | 嗨 {0},你看起来不错'
		},
		fallback: '这是备选 | 这是一个复数备选'
	},
	message: {
		hello: '世界',
		helloName: '你好,{name}',
		hoge: 'hoge',
		link: '@:message.hello',
		linkHelloName: '@:message.helloName',
		linkLinkHelloName: '@:message.linkHelloName',
		linkEnd: '这是一个链接翻译到 @:message.hello',
		linkWithin: '难道我们不是生活在美好的世界里吗?',
		linkMultiple: '你好,@:message.hoge!难道 @:message.hello 不美好吗?',
		linkBrackets: '你好,@:(message.hoge)。难道 @:(message.hello) 不美好吗?',
		linkHyphen: '@:hyphen-hello',
		linkUnderscore: '@:underscore_hello',
		linkPipe: '@:pipe|hello',
		linkColon: '@:(colon:hello)',
		linkList: '@:message.hello:{0} {1}',
		linkCaseLower: '请提供 @.lower:message.homeAddress',
		linkCaseUpper: '@.upper:message.homeAddress',
		linkCaseCapitalize: '@.capitalize:message.homeAddress',
		linkCaseUnknown: '@.unknown:message.homeAddress',
		linkCaseCustom: '@.custom:message.homeAddress',
		homeAddress: '家庭地址',
		circular1: 'Foo @:message.circular2',
		circular2: 'Bar @:message.circular3',
		circular3: 'Buz @:message.circular1',
		linkTwice: '@:message.hello:@:message.hello',
	}
};

index.uts代码如下:

import { createI18n } from '@/uni_modules/lime-i18n/index.uts'
// import { createI18n, setLocaleMessage } from '../index.uts'

import zhCN from './zh-CN'
import enUS from './en_US'

const i18n = createI18n({
	locale: uni.getStorageSync('uVueI18nLocale').toString().length != 0 ? uni.getStorageSync('uVueI18nLocale') : 'zh-CN', // 默认显示语言
	fallbackLocale: 'en-US',
	// Key - 在这种情况下,用于规则 `'ru'` 的语言
	// Value - 选择正确的复数形式的功能
	pluralizationRules: {
		/**
		 * @param choice {number} 输入给$的选择索引 $tc:`$tc('path.to.rule', choiceIndex)`
		 * @param choicesLength {number} 可用选择总数
		 * @returns 最终选择索引以选择复数单词
		 */
		'ru': function (choice : number, choicesLength : number) : number {
			if (choice == 0) {
				return 0;
			}
			const teen = choice > 10 && choice < 20;
			const endsWithOne = (choice % 10) == 1;

			if (choicesLength < 4) {
				return (!teen && endsWithOne) ? 1 : 2;
			}
			if (!teen && endsWithOne) {
				return 1;
			}
			if (!teen && (choice % 10) >= 2 && (choice % 10) <= 4) {
				return 2;
			}

			return (choicesLength < 4) ? 2 : 3;
		}
	},
	messages: {
		'zh-CN': zhCN,
		'en-US': enUS,
		'ru': {
			car: '0 машин | {n} машина | {n} машины | {n} машин',
			banana: 'нет бананов | {n} банан | {n} банана | {n} бананов'
		}
	},
	modifiers: {
		snakeCase: (str : string) : string => str.split(' ').join('_')
	},
	numberFormats: {
		'en-US': {
			currency: {
				style: 'currency', currency: 'USD', notation: 'standard'
			},
			decimal: {
				style: 'decimal', minimumFractionDigits: 2, maximumFractionDigits: 2
			},
			percent: {
				style: 'percent', useGrouping: false
			}
		},
		'zh-CN': {
			currency: {
				style: 'currency', currency: 'CNY', useGrouping: true, currencyDisplay: 'symbol'
			},
			decimal: {
				style: 'decimal', minimumSignificantDigits: 3, maximumSignificantDigits: 5
			},
			percent: {
				style: 'percent', useGrouping: false
			}
		}
	},
	datetimeFormats: {
		'en-US': {
			short: {
				year: 'numeric', month: 'short', day: 'numeric'
			},
			long: {
				year: 'numeric', month: 'short', day: 'numeric',
				weekday: 'short', hour: 'numeric', minute: 'numeric'
			}
		},
		'zh-CN': {
			short: {
				year: 'numeric', month: 'short', day: 'numeric'
			},
			long: {
				year: 'numeric', month: 'short', day: 'numeric',
				weekday: 'short', hour: 'numeric', minute: 'numeric', hour12: true
			}
		}
	},
	tabBars: {
		'en-US': ['Home','Exam','User'],
		'zh-CN': ['首页','考核','用户'],
	}
})

export default i18n



setTimeout(() => {
	// console.log('getLocale:::', uni.getLocale())
	console.log('getLocale:::',typeof uni.getStorageSync('lllluVueI18nLocale'))
	// console.log('i18n install', i18n.global)
	// setLocaleMessage('zh-CN', zhCN)
	i18n.global.locale.value = 'zh-CN'
	console.log('i18n', i18n)
}, 5000)

3、main.uts的代码修改如下:

import { createSSRApp } from 'vue'
import App from './App.uvue'
import i18n from '@/locales/index.uts'


export function createApp() {
	const app = createSSRApp(App)
	
	app.use(i18n);

	return {
		app
	}
}

4、user.uvue页面代码如下:

<template>
	<view style="flex: 1">
		<view>
			<text>测试:{{ $t('headMenus.userName') }}</text>
			<button @click="$locale.value = $locale.value != 'zh-CN' ? 'zh-CN' : 'en-US'">切换{{$locale}}</button>
		</view>
	</view>
</template>

<script lang="uts">

</script>

5、完成上述内容后,你会发现TabBar已经可以动态切换中英文了。但是NavigationBarTitle并没有跟着动态切换。

6、让NavigationBarTitle动起来。在uni_modules\lime-i18n\common\composer.uts中修改setTabBarItems函数,代码如下:

function setTabBarItems(tabbar : string[] | null) {
	if (tabbar == null) return
	const pages = getCurrentPages()
	const page = pages.length > 0 ? pages[pages.length - 1]: null;
	// @ts-ignore
	// #ifndef APP-ANDROID
	const isTabBar = page != null //page.$vm.$basePage.openType == 'switchTab'// page != null && page.$page.meta.isTabBar
	// #endif
	// #ifdef APP-ANDROID
	const isTabBar = page != null
	// #endif
	if(!isTabBar) return
	tabbar.forEach((text, index) => {
		uni.setTabBarItem({
			text,
			index,
			// success() {},
			fail(err) {
				warn(err.errMsg)
			}
		} as SetTabBarItemOptions)
		//用于切换NavigationBarTitle
		uni.setNavigationBarTitle({
			title:text,
		});
	})
}

7、好吧,我承认,en_US.uts、zh-CN.uts和index.uts是从插件的uni_modules\lime-i18n\test文件夹中的内容。

Logo

腾讯云面向开发者汇聚海量精品云计算使用和开发经验,营造开放的云计算技术生态圈。

更多推荐