小程序的国际化i18n的使用,js的data里绑定i18n国际化数据
1.i18n国际化数据文件:locales.wxs和locales.js
- locales.wxs用到.wxml文件中,locales.js用到.js文件中
locales.wxs文件的代码如下:
var fallbackLocale = 'zh-CN';
var translations = {
"en-US": {
"logo.title": "title",
},
"zh-CN": {
"logo.title": "标题",
};
var Interpreter = function (r) {
var i = "";
function o(r, n) {
return r ? "string" == typeof r ? r : r.reduce(function (r, t) {
return r.concat([function (n, e) {
if (e = e || {}, "string" == typeof n) return n;
if (n[2] && "object" == typeof n[2]) {
var r = Object.keys(n[2]).reduce(function (r, t) {
return r[t] = o(n[2][t], e), r
}, {}),
t = r[e[0]],
u = e[n[0]];
return void 0 !== u ? r[u.toString()] || r.other || i : t || (r.other || i)
}
if ("object" == typeof n && 0 < n.length) {
return function r(t, n, e) {
void 0 === e && (e = 0);
if (!n || !t || t.length <= 0) return "";
var u = n[t[e]];
if (!u) return "{" + t.join(".") + "}";
if ("string" == typeof u) return u;
if ("number" == typeof u) return u.toString();
return r(t, u, ++e)
}(n[0].split("."), e, 0)
}
return ""
}(t, n)])
}, []).join("") : i
}
function f(r, t, n) {
var e = r[t];
if (!e) return n;
var u = e[n];
return u || n
}
return r.getMessageInterpreter = function (e, u) {
function i(r, t, n) {
return o(function (r, t, n, e) {
var u = t[n];
if (!u) return f(t, e, r);
var i = u[r];
return i || f(t, e, r)
}(r, e, n, u), t)
}
return function (r, t, n) {
return 2 === arguments.length ? i(r, null, t) : 3 !== arguments.length ? "" : i(r, t, n)
}
}, r
}({});
module.exports.t = Interpreter.getMessageInterpreter(translations, fallbackLocale)
locales.js代码如下:
module.exports.fallbackLocale = 'zh-CN';
module.exports.defaultLocale = 'zh-CN';
module.exports.translations = {
"en-US": {
/**
* 轮胎
*/
"app.tyre.Mileage": 'Mileage',
},
"zh-CN": {
/**
* 轮胎
*/
"app.tyre.Mileage": '里程',
}
};
2.在.wxml中使用locales.wxs
头部引入:
<wxs src="../../i18n/locales.wxs" module="i18n" />
使用:i18n.t(“logo.title”,$_locale)
<view class="flex-item text-overflow">{{i18n.t("logo.title",$_locale)}}</view>
3.在.js中使用locales.js
头部引入:
import {
I18n,
getI18nInstance
} from '@miniprogram-i18n/core';
注入:
behaviors: [I18n], // 注入
在方法中使用,this
就已经有了I18n
暴露的方法t()
,也可用“I18n.t()
”,例如:
onShow: function () {
wx.setNavigationBarTitle({
title: this.t('app.tyre.Mileage'), // this.t('app.tyre.Mileage') 就可得到'Mileage'或'里程',也可使用I18n.t('app.tyre.Mileage')
});
}
但这种方法不适用于与在Page({data:{// 变量初始化}})
,因为data作为对象,this会指向data对象,所以不行。这个时候需要全局实例化引入的getI18nInstance()
,然后在使用。还可以通过this.setData()
实现
方法一、实例化:
const II18n = getI18nInstance();
Page({
data:{
mileage.("app.tyre.Mileage"), // 可得到'Mileage'或'里程'
}
})
方法二、this.setData()
this.setData({
mileage.("app.tyre.Mileage"), // 可得到'Mileage'或'里程'
});