refactor(privacy-popup): 抽取通用延迟i18n混入并重构隐私弹窗
1. 新建通用的i18n延迟初始化混入,解决小程序/鸿蒙环境下i18n空串缓存问题 2. 将隐私弹窗原有的prepareI18n逻辑迁移到混入中,统一实现i18nPrepareFn 3. 简化弹窗组件内的i18n处理代码,优化可维护性
This commit is contained in:
71
common/mixin/i18n-lazy.js
Normal file
71
common/mixin/i18n-lazy.js
Normal file
@@ -0,0 +1,71 @@
|
||||
/**
|
||||
* 延迟初始化 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
|
||||
* methods: {
|
||||
* i18nPrepareFn() {
|
||||
* return {
|
||||
* title: this.$lang('components.foo.title'),
|
||||
* descPrefix: this.$lang('components.foo.descPrefix', { appName: '本应用' }),
|
||||
* privacyContractName: this.platformContractName || this.$lang('components.foo.default'),
|
||||
* };
|
||||
* },
|
||||
* }
|
||||
*
|
||||
* // 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();
|
||||
},
|
||||
},
|
||||
};
|
||||
Reference in New Issue
Block a user