本次提交对全项目的国际化调用进行了规范化重构:
1. 为中文/英文语言包新增了avatar和gender的别名映射,兼容旧有headImg/sex写法
2. 修正了lang.js中的注释路径错误
3. 将所有页面和组件内的$lang调用从短路径改为带业务模块前缀的完整命名空间路径,例如将$lang('title')改为$lang('article.list.title')
4. 优化了i18n-lazy.js的注释说明,补充了正确的key命名格式示例
5. 统一了分销、订单、会员等模块的国际化key层级,确保所有语言调用路径一致
74 lines
2.4 KiB
JavaScript
74 lines
2.4 KiB
JavaScript
/**
|
|
* 延迟初始化 i18n mixin
|
|
*
|
|
* 问题背景:
|
|
* 微信小程序/鸿蒙元服务环境下, main.js 同步 $mount() 会导致组件 data() 在
|
|
* Lang.boot() 完成前求值. 此时 $lang() 在 remote-only 模式下返回空串,
|
|
* 把空串缓存到 data 字段后, 后续 boot 完成的 $forceUpdate 也无法让它重算.
|
|
*
|
|
* 解决思路:
|
|
* data() 中不能调 $lang(), 否则空串被永久缓存.
|
|
* 模板只读 this.i18n.xxx(始终是字符串, 初值为空).
|
|
* 需要显示前, 显式调一次 this.prepareI18n() — 此时 boot 必然已完成.
|
|
*
|
|
* 用法:
|
|
*
|
|
* // 1) 在 data() 中:
|
|
* data() {
|
|
* return {
|
|
* i18n: {
|
|
* title: '',
|
|
* descPrefix: '',
|
|
* privacyContractName: '',
|
|
* },
|
|
* // 准备文案时需要的动态上下文(可选)
|
|
* platformContractName: '',
|
|
* };
|
|
* }
|
|
*
|
|
* // 2) 在 methods 中实现 i18nPrepareFn, 返回一个新对象用于填充 this.i18n
|
|
* // 其中 key 用反引号 `` `your.module.title` `` 这类命名代表"业务模块的真实 key",
|
|
* // 请用业务组件实际使用的 key 替换(例如 'components.privacyPopup.title')
|
|
* methods: {
|
|
* i18nPrepareFn() {
|
|
* return {
|
|
* title: this.$lang(`your.module.title`),
|
|
* descPrefix: this.$lang('components.privacyPopup.descPrefix', { appName: '本应用' }),
|
|
* privacyContractName: this.platformContractName || this.$lang(`your.module.defaultContract`),
|
|
* };
|
|
* },
|
|
* }
|
|
*
|
|
* // 3) 在需要显示前调 this.prepareI18n()(来自 mixin)
|
|
* // 此时 Lang.boot() 必然已完成, $lang() 返回真实翻译
|
|
* popUp() {
|
|
* this.prepareI18n();
|
|
* this.showPop = true;
|
|
* }
|
|
*
|
|
* 模板中只读 i18n.xxx:
|
|
* ```html
|
|
* <view>{{ i18n.title }}</view>
|
|
* <view>{{ i18n.descPrefix }}</view>
|
|
* ```
|
|
*/
|
|
export default {
|
|
methods: {
|
|
/**
|
|
* 一次性计算所有 i18n 文案并写入 this.i18n
|
|
* 关键: 调用时机必须是 boot 完成之后(否则会缓存空串)
|
|
* 模板中读 this.i18n.xxx 永远拿到字符串
|
|
*
|
|
* 业务组件需要实现 i18nPrepareFn() 方法,
|
|
* 返回一个对象, key 与 data().i18n 字段一一对应
|
|
*/
|
|
prepareI18n() {
|
|
if (typeof this.i18nPrepareFn !== 'function') {
|
|
console.warn('[i18n-lazy] i18nPrepareFn() not implemented; this.i18n will not be filled');
|
|
return;
|
|
}
|
|
this.i18n = this.i18nPrepareFn();
|
|
},
|
|
},
|
|
};
|