提交 fd8d558f 编写于 作者: fxy060608's avatar fxy060608

wip(i18n): mp

上级 0afa02f1
const path = require('path') const path = require('path')
const json = require('@rollup/plugin-json') const json = require('@rollup/plugin-json')
const alias = require('@rollup/plugin-alias') const alias = require('@rollup/plugin-alias')
const replace = require('@rollup/plugin-replace') const replace = require('@rollup/plugin-replace')
...@@ -75,7 +75,7 @@ module.exports = { ...@@ -75,7 +75,7 @@ module.exports = {
find: 'uni-helpers', find: 'uni-helpers',
replacement: path.resolve(__dirname, '../src/core/helpers') replacement: path.resolve(__dirname, '../src/core/helpers')
}] }]
}), }),
json(), json(),
replace({ replace({
__GLOBAL__: platform.prefix, __GLOBAL__: platform.prefix,
...@@ -84,5 +84,5 @@ module.exports = { ...@@ -84,5 +84,5 @@ module.exports = {
__PLATFORM__: JSON.stringify(process.env.UNI_PLATFORM) __PLATFORM__: JSON.stringify(process.env.UNI_PLATFORM)
}) })
], ],
external: ['vue'] external: ['vue', '@dcloudio/uni-i18n']
} }
import Vue from 'vue'; import Vue from 'vue';
import { initVueI18n } from '@dcloudio/uni-i18n';
function b64DecodeUnicode (str) { function b64DecodeUnicode (str) {
return decodeURIComponent(atob(str).split('').map(function (c) { return decodeURIComponent(atob(str).split('').map(function (c) {
...@@ -192,7 +193,7 @@ function queue (hooks, data) { ...@@ -192,7 +193,7 @@ function queue (hooks, data) {
} }
if (res === false) { if (res === false) {
return { return {
then () {} then () { }
} }
} }
} }
...@@ -240,15 +241,15 @@ function getApiInterceptorHooks (method) { ...@@ -240,15 +241,15 @@ function getApiInterceptorHooks (method) {
if (hook !== 'returnValue') { if (hook !== 'returnValue') {
interceptor[hook] = globalInterceptors[hook].slice(); interceptor[hook] = globalInterceptors[hook].slice();
} }
}); });
const scopedInterceptor = scopedInterceptors[method]; const scopedInterceptor = scopedInterceptors[method];
if (scopedInterceptor) { if (scopedInterceptor) {
Object.keys(scopedInterceptor).forEach(hook => { Object.keys(scopedInterceptor).forEach(hook => {
if (hook !== 'returnValue') { if (hook !== 'returnValue') {
interceptor[hook] = (interceptor[hook] || []).concat(scopedInterceptor[hook]); interceptor[hook] = (interceptor[hook] || []).concat(scopedInterceptor[hook]);
} }
}); });
} }
return interceptor return interceptor
} }
...@@ -272,16 +273,20 @@ const promiseInterceptor = { ...@@ -272,16 +273,20 @@ const promiseInterceptor = {
if (!isPromise(res)) { if (!isPromise(res)) {
return res return res
} }
return res.then(res => { return new Promise((resolve, reject) => {
return res[1] res.then(res => {
}).catch(res => { if (res[0]) {
return res[0] reject(res[0]);
} else {
resolve(res[1]);
}
});
}) })
} }
}; };
const SYNC_API_RE = const SYNC_API_RE =
/^\$|Window$|WindowStyle$|sendNativeEvent|restoreGlobal|getCurrentSubNVue|getMenuButtonBoundingClientRect|^report|interceptors|Interceptor$|getSubNVueById|requireNativePlugin|upx2px|hideKeyboard|canIUse|^create|Sync$|Manager$|base64ToArrayBuffer|arrayBufferToBase64/; /^\$|Window$|WindowStyle$|sendNativeEvent|restoreGlobal|getCurrentSubNVue|getMenuButtonBoundingClientRect|^report|interceptors|Interceptor$|getSubNVueById|requireNativePlugin|upx2px|hideKeyboard|canIUse|^create|Sync$|Manager$|base64ToArrayBuffer|arrayBufferToBase64|getLocale|setLocale/;
const CONTEXT_API_RE = /^create|Manager$/; const CONTEXT_API_RE = /^create|Manager$/;
...@@ -394,6 +399,40 @@ function upx2px (number, newDeviceWidth) { ...@@ -394,6 +399,40 @@ function upx2px (number, newDeviceWidth) {
return number < 0 ? -result : result return number < 0 ? -result : result
} }
function getLocale () {
// 优先使用 $locale
const app = getApp({
allowDefault: true
});
if (app && app.$vm) {
return app.$vm.$locale
}
return wx.getSystemInfoSync().language || 'zh-Hans'
}
function setLocale (locale) {
const app = getApp();
if (!app) {
return false
}
const oldLocale = app.$vm.$locale;
if (oldLocale !== locale) {
app.$vm.$locale = locale;
onLocaleChangeCallbacks.forEach((fn) => fn({
locale
}));
return true
}
return false
}
const onLocaleChangeCallbacks = [];
function onLocaleChange (fn) {
if (onLocaleChangeCallbacks.indexOf(fn) === -1) {
onLocaleChangeCallbacks.push(fn);
}
}
const interceptors = { const interceptors = {
promiseInterceptor promiseInterceptor
}; };
...@@ -401,6 +440,9 @@ const interceptors = { ...@@ -401,6 +440,9 @@ const interceptors = {
var baseApi = /*#__PURE__*/Object.freeze({ var baseApi = /*#__PURE__*/Object.freeze({
__proto__: null, __proto__: null,
upx2px: upx2px, upx2px: upx2px,
getLocale: getLocale,
setLocale: setLocale,
onLocaleChange: onLocaleChange,
addInterceptor: addInterceptor, addInterceptor: addInterceptor,
removeInterceptor: removeInterceptor, removeInterceptor: removeInterceptor,
interceptors: interceptors interceptors: interceptors
...@@ -662,7 +704,7 @@ function initTriggerEvent (mpInstance) { ...@@ -662,7 +704,7 @@ function initTriggerEvent (mpInstance) {
}; };
} }
function initHook (name, options) { function initHook (name, options, isComponent) {
const oldHook = options[name]; const oldHook = options[name];
if (!oldHook) { if (!oldHook) {
options[name] = function () { options[name] = function () {
...@@ -1232,6 +1274,226 @@ function handleEvent (event) { ...@@ -1232,6 +1274,226 @@ function handleEvent (event) {
} }
} }
var en = {
"uni.app.quit": "Press back button again to exit",
"uni.async.error": "The connection timed out, click the screen to try again.",
"uni.showActionSheet.cancel": "Cancel",
"uni.showToast.unpaired": "Please note showToast must be paired with hideToast",
"uni.showLoading.unpaired": "Please note showLoading must be paired with hideLoading",
"uni.showModal.cancel": "Cancel",
"uni.showModal.confirm": "OK",
"uni.chooseImage.cancel": "Cancel",
"uni.chooseImage.sourceType.album": "Album",
"uni.chooseImage.sourceType.camera": "Camera",
"uni.chooseVideo.cancel": "Cancel",
"uni.chooseVideo.sourceType.album": "Album",
"uni.chooseVideo.sourceType.camera": "Camera",
"uni.previewImage.cancel": "Cancel",
"uni.previewImage.button.save": "Save Image",
"uni.previewImage.save.success": "Saved successfully",
"uni.previewImage.save.fail": "Save failed",
"uni.setClipboardData.success": "Content copied",
"uni.scanCode.title": "Scan code",
"uni.scanCode.album": "Album",
"uni.scanCode.fail": "Recognition failure",
"uni.scanCode.flash.on": "Tap to turn light on",
"uni.scanCode.flash.off": "Tap to turn light off",
"uni.startSoterAuthentication.authContent": "Fingerprint recognition",
"uni.picker.done": "Done",
"uni.picker.cancel": "Cancel",
"uni.video.danmu": "Danmu",
"uni.video.volume": "Volume",
"uni.button.feedback.title": "feedback",
"uni.button.feedback.send": "send"
};
var es = {
"uni.app.quit": "Pulse otra vez para salir",
"uni.async.error": "Se agotó el tiempo de conexión, haga clic en la pantalla para volver a intentarlo.",
"uni.showActionSheet.cancel": "Cancelar",
"uni.showToast.unpaired": "Tenga en cuenta que showToast debe estar emparejado con hideToast",
"uni.showLoading.unpaired": "Tenga en cuenta que showLoading debe estar emparejado con hideLoading",
"uni.showModal.cancel": "Cancelar",
"uni.showModal.confirm": "OK",
"uni.chooseImage.cancel": "Cancelar",
"uni.chooseImage.sourceType.album": "Álbum",
"uni.chooseImage.sourceType.camera": "Cámara",
"uni.chooseVideo.cancel": "Cancelar",
"uni.chooseVideo.sourceType.album": "Álbum",
"uni.chooseVideo.sourceType.camera": "Cámara",
"uni.previewImage.cancel": "Cancelar",
"uni.previewImage.button.save": "Guardar imagen",
"uni.previewImage.save.success": "Guardado exitosamente",
"uni.previewImage.save.fail": "Error al guardar",
"uni.setClipboardData.success": "Contenido copiado",
"uni.scanCode.title": "Código de escaneo",
"uni.scanCode.album": "Álbum",
"uni.scanCode.fail": "Échec de la reconnaissance",
"uni.scanCode.flash.on": "Toque para encender la luz",
"uni.scanCode.flash.off": "Toque para apagar la luz",
"uni.startSoterAuthentication.authContent": "Reconocimiento de huellas dactilares",
"uni.picker.done": "OK",
"uni.picker.cancel": "Cancelar",
"uni.video.danmu": "Danmu",
"uni.video.volume": "Volumen",
"uni.button.feedback.title": "realimentación",
"uni.button.feedback.send": "enviar"
};
var fr = {
"uni.app.quit": "Appuyez à nouveau pour quitter l'application",
"uni.async.error": "La connexion a expiré, cliquez sur l'écran pour réessayer.",
"uni.showActionSheet.cancel": "Annuler",
"uni.showToast.unpaired": "Veuillez noter que showToast doit être associé à hideToast",
"uni.showLoading.unpaired": "Veuillez noter que showLoading doit être associé à hideLoading",
"uni.showModal.cancel": "Annuler",
"uni.showModal.confirm": "OK",
"uni.chooseImage.cancel": "Annuler",
"uni.chooseImage.sourceType.album": "Album",
"uni.chooseImage.sourceType.camera": "Caméra",
"uni.chooseVideo.cancel": "Annuler",
"uni.chooseVideo.sourceType.album": "Album",
"uni.chooseVideo.sourceType.camera": "Caméra",
"uni.previewImage.cancel": "Annuler",
"uni.previewImage.button.save": "Guardar imagen",
"uni.previewImage.save.success": "Enregistré avec succès",
"uni.previewImage.save.fail": "Échec de la sauvegarde",
"uni.setClipboardData.success": "Contenu copié",
"uni.scanCode.title": "Code d’analyse",
"uni.scanCode.album": "Album",
"uni.scanCode.fail": "Fallo de reconocimiento",
"uni.scanCode.flash.on": "Appuyez pour activer l'éclairage",
"uni.scanCode.flash.off": "Appuyez pour désactiver l'éclairage",
"uni.startSoterAuthentication.authContent": "Reconnaissance de l'empreinte digitale",
"uni.picker.done": "OK",
"uni.picker.cancel": "Annuler",
"uni.video.danmu": "Danmu",
"uni.video.volume": "Le Volume",
"uni.button.feedback.title": "retour d'information",
"uni.button.feedback.send": "envoyer"
};
var zhHans = {
"uni.app.quit": "再按一次退出应用",
"uni.async.error": "连接服务器超时,点击屏幕重试",
"uni.showActionSheet.cancel": "取消",
"uni.showToast.unpaired": "请注意 showToast 与 hideToast 必须配对使用",
"uni.showLoading.unpaired": "请注意 showLoading 与 hideLoading 必须配对使用",
"uni.showModal.cancel": "取消",
"uni.showModal.confirm": "确定",
"uni.chooseImage.cancel": "取消",
"uni.chooseImage.sourceType.album": "从相册选择",
"uni.chooseImage.sourceType.camera": "拍摄",
"uni.chooseVideo.cancel": "取消",
"uni.chooseVideo.sourceType.album": "从相册选择",
"uni.chooseVideo.sourceType.camera": "拍摄",
"uni.previewImage.cancel": "取消",
"uni.previewImage.button.save": "保存图像",
"uni.previewImage.save.success": "保存图像到相册成功",
"uni.previewImage.save.fail": "保存图像到相册失败",
"uni.setClipboardData.success": "内容已复制",
"uni.scanCode.title": "扫码",
"uni.scanCode.album": "相册",
"uni.scanCode.fail": "识别失败",
"uni.scanCode.flash.on": "轻触照亮",
"uni.scanCode.flash.off": "轻触关闭",
"uni.startSoterAuthentication.authContent": "指纹识别中...",
"uni.picker.done": "完成",
"uni.picker.cancel": "取消",
"uni.video.danmu": "弹幕",
"uni.video.volume": "音量",
"uni.button.feedback.title": "问题反馈",
"uni.button.feedback.send": "发送"
};
var zhHant = {
"uni.app.quit": "再按一次退出應用",
"uni.async.error": "連接服務器超時,點擊屏幕重試",
"uni.showActionSheet.cancel": "取消",
"uni.showToast.unpaired": "請注意 showToast 與 hideToast 必須配對使用",
"uni.showLoading.unpaired": "請注意 showLoading 與 hideLoading 必須配對使用",
"uni.showModal.cancel": "取消",
"uni.showModal.confirm": "確定",
"uni.chooseImage.cancel": "取消",
"uni.chooseImage.sourceType.album": "從相冊選擇",
"uni.chooseImage.sourceType.camera": "拍攝",
"uni.chooseVideo.cancel": "取消",
"uni.chooseVideo.sourceType.album": "從相冊選擇",
"uni.chooseVideo.sourceType.camera": "拍攝",
"uni.previewImage.cancel": "取消",
"uni.previewImage.button.save": "保存圖像",
"uni.previewImage.save.success": "保存圖像到相冊成功",
"uni.previewImage.save.fail": "保存圖像到相冊失敗",
"uni.setClipboardData.success": "內容已復制",
"uni.scanCode.title": "掃碼",
"uni.scanCode.album": "相冊",
"uni.scanCode.fail": "識別失敗",
"uni.scanCode.flash.on": "輕觸照亮",
"uni.scanCode.flash.off": "輕觸關閉",
"uni.startSoterAuthentication.authContent": "指紋識別中...",
"uni.picker.done": "完成",
"uni.picker.cancel": "取消",
"uni.video.danmu": "彈幕",
"uni.video.volume": "音量",
"uni.button.feedback.title": "問題反饋",
"uni.button.feedback.send": "發送"
};
const messages = {
en,
es,
fr,
'zh-Hans': zhHans,
'zh-Hant': zhHant
};
let locale;
{
if (typeof weex === 'object') {
locale = weex.requireModule('plus').getLanguage();
}
}
const i18n = initVueI18n(locale, messages );
const t = i18n.t;
const i18nMixin = i18n.mixin = {
beforeCreate () {
const unwatch = i18n.i18n.watchLocale(() => {
this.$forceUpdate();
});
this.$once('hook:beforeDestroy', function () {
unwatch();
});
},
methods: {
$$t (key, values) {
return t(key, values)
}
}
};
const setLocale$1 = i18n.setLocale;
const getLocale$1 = i18n.getLocale;
function initAppLocale (Vue, appVm, locale) {
const state = Vue.observable({
locale: locale || i18n.getLocale()
});
const localeWatchers = [];
appVm.$watchLocale = (fn) => {
localeWatchers.push(fn);
};
Object.defineProperty(appVm, '$locale', {
get () {
return state.locale
},
set (v) {
state.locale = v;
localeWatchers.forEach(watch => watch(v));
}
});
}
class EventChannel { class EventChannel {
constructor (id, events) { constructor (id, events) {
this.id = id; this.id = id;
...@@ -1414,6 +1676,8 @@ function parseBaseApp (vm, { ...@@ -1414,6 +1676,8 @@ function parseBaseApp (vm, {
}); });
} }
initAppLocale(Vue, vm, wx.getSystemInfoSync().language || 'zh-Hans');
initHooks(appOptions, hooks); initHooks(appOptions, hooks);
return appOptions return appOptions
......
...@@ -1666,9 +1666,9 @@ var serviceContext = (function () { ...@@ -1666,9 +1666,9 @@ var serviceContext = (function () {
}; };
const getLocale = i18n.getLocale; const getLocale = i18n.getLocale;
function initAppLocale (Vue, appVm) { function initAppLocale (Vue, appVm, locale) {
const state = Vue.observable({ const state = Vue.observable({
locale: i18n.getLocale() locale: locale || i18n.getLocale()
}); });
const localeWatchers = []; const localeWatchers = [];
appVm.$watchLocale = (fn) => { appVm.$watchLocale = (fn) => {
......
import Vue from 'vue'; import Vue from 'vue';
import { initVueI18n } from '@dcloudio/uni-i18n';
function b64DecodeUnicode (str) { function b64DecodeUnicode (str) {
return decodeURIComponent(atob(str).split('').map(function (c) { return decodeURIComponent(atob(str).split('').map(function (c) {
...@@ -192,7 +193,7 @@ function queue (hooks, data) { ...@@ -192,7 +193,7 @@ function queue (hooks, data) {
} }
if (res === false) { if (res === false) {
return { return {
then () {} then () { }
} }
} }
} }
...@@ -240,15 +241,15 @@ function getApiInterceptorHooks (method) { ...@@ -240,15 +241,15 @@ function getApiInterceptorHooks (method) {
if (hook !== 'returnValue') { if (hook !== 'returnValue') {
interceptor[hook] = globalInterceptors[hook].slice(); interceptor[hook] = globalInterceptors[hook].slice();
} }
}); });
const scopedInterceptor = scopedInterceptors[method]; const scopedInterceptor = scopedInterceptors[method];
if (scopedInterceptor) { if (scopedInterceptor) {
Object.keys(scopedInterceptor).forEach(hook => { Object.keys(scopedInterceptor).forEach(hook => {
if (hook !== 'returnValue') { if (hook !== 'returnValue') {
interceptor[hook] = (interceptor[hook] || []).concat(scopedInterceptor[hook]); interceptor[hook] = (interceptor[hook] || []).concat(scopedInterceptor[hook]);
} }
}); });
} }
return interceptor return interceptor
} }
...@@ -272,16 +273,20 @@ const promiseInterceptor = { ...@@ -272,16 +273,20 @@ const promiseInterceptor = {
if (!isPromise(res)) { if (!isPromise(res)) {
return res return res
} }
return res.then(res => { return new Promise((resolve, reject) => {
return res[1] res.then(res => {
}).catch(res => { if (res[0]) {
return res[0] reject(res[0]);
} else {
resolve(res[1]);
}
});
}) })
} }
}; };
const SYNC_API_RE = const SYNC_API_RE =
/^\$|Window$|WindowStyle$|sendNativeEvent|restoreGlobal|getCurrentSubNVue|getMenuButtonBoundingClientRect|^report|interceptors|Interceptor$|getSubNVueById|requireNativePlugin|upx2px|hideKeyboard|canIUse|^create|Sync$|Manager$|base64ToArrayBuffer|arrayBufferToBase64/; /^\$|Window$|WindowStyle$|sendNativeEvent|restoreGlobal|getCurrentSubNVue|getMenuButtonBoundingClientRect|^report|interceptors|Interceptor$|getSubNVueById|requireNativePlugin|upx2px|hideKeyboard|canIUse|^create|Sync$|Manager$|base64ToArrayBuffer|arrayBufferToBase64|getLocale|setLocale/;
const CONTEXT_API_RE = /^create|Manager$/; const CONTEXT_API_RE = /^create|Manager$/;
...@@ -394,6 +399,40 @@ function upx2px (number, newDeviceWidth) { ...@@ -394,6 +399,40 @@ function upx2px (number, newDeviceWidth) {
return number < 0 ? -result : result return number < 0 ? -result : result
} }
function getLocale () {
// 优先使用 $locale
const app = getApp({
allowDefault: true
});
if (app && app.$vm) {
return app.$vm.$locale
}
return swan.getSystemInfoSync().language || 'zh-Hans'
}
function setLocale (locale) {
const app = getApp();
if (!app) {
return false
}
const oldLocale = app.$vm.$locale;
if (oldLocale !== locale) {
app.$vm.$locale = locale;
onLocaleChangeCallbacks.forEach((fn) => fn({
locale
}));
return true
}
return false
}
const onLocaleChangeCallbacks = [];
function onLocaleChange (fn) {
if (onLocaleChangeCallbacks.indexOf(fn) === -1) {
onLocaleChangeCallbacks.push(fn);
}
}
const interceptors = { const interceptors = {
promiseInterceptor promiseInterceptor
}; };
...@@ -401,6 +440,9 @@ const interceptors = { ...@@ -401,6 +440,9 @@ const interceptors = {
var baseApi = /*#__PURE__*/Object.freeze({ var baseApi = /*#__PURE__*/Object.freeze({
__proto__: null, __proto__: null,
upx2px: upx2px, upx2px: upx2px,
getLocale: getLocale,
setLocale: setLocale,
onLocaleChange: onLocaleChange,
addInterceptor: addInterceptor, addInterceptor: addInterceptor,
removeInterceptor: removeInterceptor, removeInterceptor: removeInterceptor,
interceptors: interceptors interceptors: interceptors
...@@ -1059,7 +1101,7 @@ function initTriggerEvent (mpInstance) { ...@@ -1059,7 +1101,7 @@ function initTriggerEvent (mpInstance) {
}; };
} }
function initHook (name, options) { function initHook (name, options, isComponent) {
const oldHook = options[name]; const oldHook = options[name];
if (!oldHook) { if (!oldHook) {
options[name] = function () { options[name] = function () {
...@@ -1655,6 +1697,51 @@ function handleEvent (event) { ...@@ -1655,6 +1697,51 @@ function handleEvent (event) {
} }
} }
let locale;
{
locale = swan.getSystemInfoSync().language;
}
const i18n = initVueI18n(locale, {});
const t = i18n.t;
const i18nMixin = i18n.mixin = {
beforeCreate () {
const unwatch = i18n.i18n.watchLocale(() => {
this.$forceUpdate();
});
this.$once('hook:beforeDestroy', function () {
unwatch();
});
},
methods: {
$$t (key, values) {
return t(key, values)
}
}
};
const setLocale$1 = i18n.setLocale;
const getLocale$1 = i18n.getLocale;
function initAppLocale (Vue, appVm, locale) {
const state = Vue.observable({
locale: locale || i18n.getLocale()
});
const localeWatchers = [];
appVm.$watchLocale = (fn) => {
localeWatchers.push(fn);
};
Object.defineProperty(appVm, '$locale', {
get () {
return state.locale
},
set (v) {
state.locale = v;
localeWatchers.forEach(watch => watch(v));
}
});
}
const hooks = [ const hooks = [
'onShow', 'onShow',
'onHide', 'onHide',
...@@ -1811,6 +1898,8 @@ function parseBaseApp (vm, { ...@@ -1811,6 +1898,8 @@ function parseBaseApp (vm, {
}); });
} }
initAppLocale(Vue, vm, swan.getSystemInfoSync().language || 'zh-Hans');
initHooks(appOptions, hooks); initHooks(appOptions, hooks);
return appOptions return appOptions
...@@ -1962,6 +2051,44 @@ function stringifyQuery (obj, encodeStr = encode) { ...@@ -1962,6 +2051,44 @@ function stringifyQuery (obj, encodeStr = encode) {
return res ? `?${res}` : '' return res ? `?${res}` : ''
} }
/**
* 用于延迟调用 setData
* 在 setData 真实调用的时机需执行 fixSetDataEnd
* @param {*} mpInstance
*/
function fixSetDataStart (mpInstance) {
const setData = mpInstance.setData;
const setDataArgs = [];
mpInstance.setData = function () {
setDataArgs.push(arguments);
};
mpInstance.__fixInitData = function () {
this.setData = setData;
const fn = () => {
setDataArgs.forEach(args => {
setData.apply(this, args);
});
};
if (setDataArgs.length) {
if (this.groupSetData) {
this.groupSetData(fn);
} else {
fn();
}
}
};
}
/**
* 恢复真实的 setData 方法
* @param {*} mpInstance
*/
function fixSetDataEnd (mpInstance) {
if (mpInstance.__fixInitData) {
mpInstance.__fixInitData();
delete mpInstance.__fixInitData;
}
}
function parseBaseComponent (vueComponentOptions, { function parseBaseComponent (vueComponentOptions, {
isPage, isPage,
initRelation initRelation
...@@ -2075,22 +2202,7 @@ function parseComponent (vueOptions) { ...@@ -2075,22 +2202,7 @@ function parseComponent (vueOptions) {
} }
// 处理百度小程序 onInit 生命周期调用 setData 无效的问题 // 处理百度小程序 onInit 生命周期调用 setData 无效的问题
const setData = this.setData; fixSetDataStart(this);
const setDataArgs = [];
this.setData = function () {
setDataArgs.push(arguments);
};
this.__fixInitData = function () {
delete this.__fixInitData;
this.setData = setData;
if (setDataArgs.length) {
this.groupSetData(() => {
setDataArgs.forEach(args => {
setData.apply(this, args);
});
});
}
};
oldAttached.call(this); oldAttached.call(this);
this.pageinstance.$vm = this.$vm; this.pageinstance.$vm = this.$vm;
this.$vm.__call_hook('onInit', query); this.$vm.__call_hook('onInit', query);
...@@ -2100,7 +2212,7 @@ function parseComponent (vueOptions) { ...@@ -2100,7 +2212,7 @@ function parseComponent (vueOptions) {
oldAttached.call(this); oldAttached.call(this);
} else { } else {
initMocks(this.$vm, mocks); initMocks(this.$vm, mocks);
this.__fixInitData && this.__fixInitData(); fixSetDataEnd(this);
} }
if (isPage.call(this)) { // 百度 onLoad 在 attached 之前触发(基础库小于 3.70) if (isPage.call(this)) { // 百度 onLoad 在 attached 之前触发(基础库小于 3.70)
// 百度 当组件作为页面时 pageinstancce 不是原来组件的 instance // 百度 当组件作为页面时 pageinstancce 不是原来组件的 instance
......
import Vue from 'vue'; import Vue from 'vue';
import { initVueI18n } from '@dcloudio/uni-i18n';
function b64DecodeUnicode (str) { function b64DecodeUnicode (str) {
return decodeURIComponent(atob(str).split('').map(function (c) { return decodeURIComponent(atob(str).split('').map(function (c) {
...@@ -285,7 +286,7 @@ const promiseInterceptor = { ...@@ -285,7 +286,7 @@ const promiseInterceptor = {
}; };
const SYNC_API_RE = const SYNC_API_RE =
/^\$|Window$|WindowStyle$|sendNativeEvent|restoreGlobal|getCurrentSubNVue|getMenuButtonBoundingClientRect|^report|interceptors|Interceptor$|getSubNVueById|requireNativePlugin|upx2px|hideKeyboard|canIUse|^create|Sync$|Manager$|base64ToArrayBuffer|arrayBufferToBase64/; /^\$|Window$|WindowStyle$|sendNativeEvent|restoreGlobal|getCurrentSubNVue|getMenuButtonBoundingClientRect|^report|interceptors|Interceptor$|getSubNVueById|requireNativePlugin|upx2px|hideKeyboard|canIUse|^create|Sync$|Manager$|base64ToArrayBuffer|arrayBufferToBase64|getLocale|setLocale/;
const CONTEXT_API_RE = /^create|Manager$/; const CONTEXT_API_RE = /^create|Manager$/;
...@@ -398,6 +399,40 @@ function upx2px (number, newDeviceWidth) { ...@@ -398,6 +399,40 @@ function upx2px (number, newDeviceWidth) {
return number < 0 ? -result : result return number < 0 ? -result : result
} }
function getLocale () {
// 优先使用 $locale
const app = getApp({
allowDefault: true
});
if (app && app.$vm) {
return app.$vm.$locale
}
return ks.getSystemInfoSync().language || 'zh-Hans'
}
function setLocale (locale) {
const app = getApp();
if (!app) {
return false
}
const oldLocale = app.$vm.$locale;
if (oldLocale !== locale) {
app.$vm.$locale = locale;
onLocaleChangeCallbacks.forEach((fn) => fn({
locale
}));
return true
}
return false
}
const onLocaleChangeCallbacks = [];
function onLocaleChange (fn) {
if (onLocaleChangeCallbacks.indexOf(fn) === -1) {
onLocaleChangeCallbacks.push(fn);
}
}
const interceptors = { const interceptors = {
promiseInterceptor promiseInterceptor
}; };
...@@ -405,6 +440,9 @@ const interceptors = { ...@@ -405,6 +440,9 @@ const interceptors = {
var baseApi = /*#__PURE__*/Object.freeze({ var baseApi = /*#__PURE__*/Object.freeze({
__proto__: null, __proto__: null,
upx2px: upx2px, upx2px: upx2px,
getLocale: getLocale,
setLocale: setLocale,
onLocaleChange: onLocaleChange,
addInterceptor: addInterceptor, addInterceptor: addInterceptor,
removeInterceptor: removeInterceptor, removeInterceptor: removeInterceptor,
interceptors: interceptors interceptors: interceptors
...@@ -838,7 +876,7 @@ function initTriggerEvent (mpInstance) { ...@@ -838,7 +876,7 @@ function initTriggerEvent (mpInstance) {
}; };
} }
function initHook (name, options) { function initHook (name, options, isComponent) {
const oldHook = options[name]; const oldHook = options[name];
if (!oldHook) { if (!oldHook) {
options[name] = function () { options[name] = function () {
...@@ -1408,6 +1446,51 @@ function handleEvent (event) { ...@@ -1408,6 +1446,51 @@ function handleEvent (event) {
} }
} }
let locale;
{
locale = ks.getSystemInfoSync().language;
}
const i18n = initVueI18n(locale, {});
const t = i18n.t;
const i18nMixin = i18n.mixin = {
beforeCreate () {
const unwatch = i18n.i18n.watchLocale(() => {
this.$forceUpdate();
});
this.$once('hook:beforeDestroy', function () {
unwatch();
});
},
methods: {
$$t (key, values) {
return t(key, values)
}
}
};
const setLocale$1 = i18n.setLocale;
const getLocale$1 = i18n.getLocale;
function initAppLocale (Vue, appVm, locale) {
const state = Vue.observable({
locale: locale || i18n.getLocale()
});
const localeWatchers = [];
appVm.$watchLocale = (fn) => {
localeWatchers.push(fn);
};
Object.defineProperty(appVm, '$locale', {
get () {
return state.locale
},
set (v) {
state.locale = v;
localeWatchers.forEach(watch => watch(v));
}
});
}
const hooks = [ const hooks = [
'onShow', 'onShow',
'onHide', 'onHide',
...@@ -1564,6 +1647,8 @@ function parseBaseApp (vm, { ...@@ -1564,6 +1647,8 @@ function parseBaseApp (vm, {
}); });
} }
initAppLocale(Vue, vm, ks.getSystemInfoSync().language || 'zh-Hans');
initHooks(appOptions, hooks); initHooks(appOptions, hooks);
return appOptions return appOptions
......
import Vue from 'vue'; import Vue from 'vue';
import { initVueI18n } from '@dcloudio/uni-i18n';
function b64DecodeUnicode (str) { function b64DecodeUnicode (str) {
return decodeURIComponent(atob(str).split('').map(function (c) { return decodeURIComponent(atob(str).split('').map(function (c) {
...@@ -192,7 +193,7 @@ function queue (hooks, data) { ...@@ -192,7 +193,7 @@ function queue (hooks, data) {
} }
if (res === false) { if (res === false) {
return { return {
then () {} then () { }
} }
} }
} }
...@@ -240,15 +241,15 @@ function getApiInterceptorHooks (method) { ...@@ -240,15 +241,15 @@ function getApiInterceptorHooks (method) {
if (hook !== 'returnValue') { if (hook !== 'returnValue') {
interceptor[hook] = globalInterceptors[hook].slice(); interceptor[hook] = globalInterceptors[hook].slice();
} }
}); });
const scopedInterceptor = scopedInterceptors[method]; const scopedInterceptor = scopedInterceptors[method];
if (scopedInterceptor) { if (scopedInterceptor) {
Object.keys(scopedInterceptor).forEach(hook => { Object.keys(scopedInterceptor).forEach(hook => {
if (hook !== 'returnValue') { if (hook !== 'returnValue') {
interceptor[hook] = (interceptor[hook] || []).concat(scopedInterceptor[hook]); interceptor[hook] = (interceptor[hook] || []).concat(scopedInterceptor[hook]);
} }
}); });
} }
return interceptor return interceptor
} }
...@@ -272,16 +273,20 @@ const promiseInterceptor = { ...@@ -272,16 +273,20 @@ const promiseInterceptor = {
if (!isPromise(res)) { if (!isPromise(res)) {
return res return res
} }
return res.then(res => { return new Promise((resolve, reject) => {
return res[1] res.then(res => {
}).catch(res => { if (res[0]) {
return res[0] reject(res[0]);
} else {
resolve(res[1]);
}
});
}) })
} }
}; };
const SYNC_API_RE = const SYNC_API_RE =
/^\$|Window$|WindowStyle$|sendNativeEvent|restoreGlobal|getCurrentSubNVue|getMenuButtonBoundingClientRect|^report|interceptors|Interceptor$|getSubNVueById|requireNativePlugin|upx2px|hideKeyboard|canIUse|^create|Sync$|Manager$|base64ToArrayBuffer|arrayBufferToBase64/; /^\$|Window$|WindowStyle$|sendNativeEvent|restoreGlobal|getCurrentSubNVue|getMenuButtonBoundingClientRect|^report|interceptors|Interceptor$|getSubNVueById|requireNativePlugin|upx2px|hideKeyboard|canIUse|^create|Sync$|Manager$|base64ToArrayBuffer|arrayBufferToBase64|getLocale|setLocale/;
const CONTEXT_API_RE = /^create|Manager$/; const CONTEXT_API_RE = /^create|Manager$/;
...@@ -394,6 +399,40 @@ function upx2px (number, newDeviceWidth) { ...@@ -394,6 +399,40 @@ function upx2px (number, newDeviceWidth) {
return number < 0 ? -result : result return number < 0 ? -result : result
} }
function getLocale () {
// 优先使用 $locale
const app = getApp({
allowDefault: true
});
if (app && app.$vm) {
return app.$vm.$locale
}
return wx.getSystemInfoSync().language || 'zh-Hans'
}
function setLocale (locale) {
const app = getApp();
if (!app) {
return false
}
const oldLocale = app.$vm.$locale;
if (oldLocale !== locale) {
app.$vm.$locale = locale;
onLocaleChangeCallbacks.forEach((fn) => fn({
locale
}));
return true
}
return false
}
const onLocaleChangeCallbacks = [];
function onLocaleChange (fn) {
if (onLocaleChangeCallbacks.indexOf(fn) === -1) {
onLocaleChangeCallbacks.push(fn);
}
}
const interceptors = { const interceptors = {
promiseInterceptor promiseInterceptor
}; };
...@@ -401,6 +440,9 @@ const interceptors = { ...@@ -401,6 +440,9 @@ const interceptors = {
var baseApi = /*#__PURE__*/Object.freeze({ var baseApi = /*#__PURE__*/Object.freeze({
__proto__: null, __proto__: null,
upx2px: upx2px, upx2px: upx2px,
getLocale: getLocale,
setLocale: setLocale,
onLocaleChange: onLocaleChange,
addInterceptor: addInterceptor, addInterceptor: addInterceptor,
removeInterceptor: removeInterceptor, removeInterceptor: removeInterceptor,
interceptors: interceptors interceptors: interceptors
...@@ -995,7 +1037,7 @@ function initTriggerEvent (mpInstance) { ...@@ -995,7 +1037,7 @@ function initTriggerEvent (mpInstance) {
}; };
} }
function initHook (name, options) { function initHook (name, options, isComponent) {
const oldHook = options[name]; const oldHook = options[name];
if (!oldHook) { if (!oldHook) {
options[name] = function () { options[name] = function () {
...@@ -1565,6 +1607,51 @@ function handleEvent (event) { ...@@ -1565,6 +1607,51 @@ function handleEvent (event) {
} }
} }
let locale;
{
locale = wx.getSystemInfoSync().language;
}
const i18n = initVueI18n(locale, {});
const t = i18n.t;
const i18nMixin = i18n.mixin = {
beforeCreate () {
const unwatch = i18n.i18n.watchLocale(() => {
this.$forceUpdate();
});
this.$once('hook:beforeDestroy', function () {
unwatch();
});
},
methods: {
$$t (key, values) {
return t(key, values)
}
}
};
const setLocale$1 = i18n.setLocale;
const getLocale$1 = i18n.getLocale;
function initAppLocale (Vue, appVm, locale) {
const state = Vue.observable({
locale: locale || i18n.getLocale()
});
const localeWatchers = [];
appVm.$watchLocale = (fn) => {
localeWatchers.push(fn);
};
Object.defineProperty(appVm, '$locale', {
get () {
return state.locale
},
set (v) {
state.locale = v;
localeWatchers.forEach(watch => watch(v));
}
});
}
const hooks = [ const hooks = [
'onShow', 'onShow',
'onHide', 'onHide',
...@@ -1726,6 +1813,8 @@ function parseBaseApp (vm, { ...@@ -1726,6 +1813,8 @@ function parseBaseApp (vm, {
}); });
} }
initAppLocale(Vue, vm, wx.getSystemInfoSync().language || 'zh-Hans');
initHooks(appOptions, hooks); initHooks(appOptions, hooks);
return appOptions return appOptions
......
import Vue from 'vue'; import Vue from 'vue';
import { initVueI18n } from '@dcloudio/uni-i18n';
function b64DecodeUnicode (str) { function b64DecodeUnicode (str) {
return decodeURIComponent(atob(str).split('').map(function (c) { return decodeURIComponent(atob(str).split('').map(function (c) {
return '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2) return '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2)
}).join('')) }).join(''))
} }
function getCurrentUserInfo () { function getCurrentUserInfo () {
const token = ( tt).getStorageSync('uni_id_token') || ''; const token = ( tt).getStorageSync('uni_id_token') || '';
const tokenArr = token.split('.'); const tokenArr = token.split('.');
if (!token || tokenArr.length !== 3) { if (!token || tokenArr.length !== 3) {
return { return {
uid: null, uid: null,
role: [], role: [],
permission: [], permission: [],
tokenExpired: 0 tokenExpired: 0
} }
} }
let userInfo; let userInfo;
try { try {
userInfo = JSON.parse(b64DecodeUnicode(tokenArr[1])); userInfo = JSON.parse(b64DecodeUnicode(tokenArr[1]));
} catch (error) { } catch (error) {
throw new Error('获取当前用户信息出错,详细错误信息为:' + error.message) throw new Error('获取当前用户信息出错,详细错误信息为:' + error.message)
} }
userInfo.tokenExpired = userInfo.exp * 1000; userInfo.tokenExpired = userInfo.exp * 1000;
delete userInfo.exp; delete userInfo.exp;
delete userInfo.iat; delete userInfo.iat;
return userInfo return userInfo
} }
function uniIdMixin (Vue) { function uniIdMixin (Vue) {
Vue.prototype.uniIDHasRole = function (roleId) { Vue.prototype.uniIDHasRole = function (roleId) {
const { const {
role role
} = getCurrentUserInfo(); } = getCurrentUserInfo();
return role.indexOf(roleId) > -1 return role.indexOf(roleId) > -1
}; };
Vue.prototype.uniIDHasPermission = function (permissionId) { Vue.prototype.uniIDHasPermission = function (permissionId) {
const { const {
permission permission
} = getCurrentUserInfo(); } = getCurrentUserInfo();
return this.uniIDHasRole('admin') || permission.indexOf(permissionId) > -1 return this.uniIDHasRole('admin') || permission.indexOf(permissionId) > -1
}; };
Vue.prototype.uniIDTokenValid = function () { Vue.prototype.uniIDTokenValid = function () {
const { const {
tokenExpired tokenExpired
} = getCurrentUserInfo(); } = getCurrentUserInfo();
return tokenExpired > Date.now() return tokenExpired > Date.now()
}; };
} }
const _toString = Object.prototype.toString; const _toString = Object.prototype.toString;
...@@ -398,6 +399,40 @@ function upx2px (number, newDeviceWidth) { ...@@ -398,6 +399,40 @@ function upx2px (number, newDeviceWidth) {
return number < 0 ? -result : result return number < 0 ? -result : result
} }
function getLocale () {
// 优先使用 $locale
const app = getApp({
allowDefault: true
});
if (app && app.$vm) {
return app.$vm.$locale
}
return tt.getSystemInfoSync().language || 'zh-Hans'
}
function setLocale (locale) {
const app = getApp();
if (!app) {
return false
}
const oldLocale = app.$vm.$locale;
if (oldLocale !== locale) {
app.$vm.$locale = locale;
onLocaleChangeCallbacks.forEach((fn) => fn({
locale
}));
return true
}
return false
}
const onLocaleChangeCallbacks = [];
function onLocaleChange (fn) {
if (onLocaleChangeCallbacks.indexOf(fn) === -1) {
onLocaleChangeCallbacks.push(fn);
}
}
const interceptors = { const interceptors = {
promiseInterceptor promiseInterceptor
}; };
...@@ -405,6 +440,9 @@ const interceptors = { ...@@ -405,6 +440,9 @@ const interceptors = {
var baseApi = /*#__PURE__*/Object.freeze({ var baseApi = /*#__PURE__*/Object.freeze({
__proto__: null, __proto__: null,
upx2px: upx2px, upx2px: upx2px,
getLocale: getLocale,
setLocale: setLocale,
onLocaleChange: onLocaleChange,
addInterceptor: addInterceptor, addInterceptor: addInterceptor,
removeInterceptor: removeInterceptor, removeInterceptor: removeInterceptor,
interceptors: interceptors interceptors: interceptors
...@@ -581,44 +619,44 @@ var previewImage = { ...@@ -581,44 +619,44 @@ var previewImage = {
} }
}; };
const UUID_KEY = '__DC_STAT_UUID'; const UUID_KEY = '__DC_STAT_UUID';
let deviceId; let deviceId;
function addUuid (result) { function addUuid (result) {
deviceId = deviceId || tt.getStorageSync(UUID_KEY); deviceId = deviceId || tt.getStorageSync(UUID_KEY);
if (!deviceId) { if (!deviceId) {
deviceId = Date.now() + '' + Math.floor(Math.random() * 1e7); deviceId = Date.now() + '' + Math.floor(Math.random() * 1e7);
tt.setStorage({ tt.setStorage({
key: UUID_KEY, key: UUID_KEY,
data: deviceId data: deviceId
}); });
} }
result.deviceId = deviceId; result.deviceId = deviceId;
} }
function addSafeAreaInsets (result) { function addSafeAreaInsets (result) {
if (result.safeArea) { if (result.safeArea) {
const safeArea = result.safeArea; const safeArea = result.safeArea;
result.safeAreaInsets = { result.safeAreaInsets = {
top: safeArea.top, top: safeArea.top,
left: safeArea.left, left: safeArea.left,
right: result.windowWidth - safeArea.right, right: result.windowWidth - safeArea.right,
bottom: result.windowHeight - safeArea.bottom bottom: result.windowHeight - safeArea.bottom
}; };
} }
} }
var getSystemInfo = { var getSystemInfo = {
returnValue: function (result) { returnValue: function (result) {
addUuid(result); addUuid(result);
addSafeAreaInsets(result); addSafeAreaInsets(result);
} }
}; };
const oName = 'getUserInfo'; const oName = 'getUserInfo';
const nName = 'getUserProfile'; const nName = 'getUserProfile';
var getUserProfile = { var getUserProfile = {
name: tt.canIUse(nName) ? nName : oName name: tt.canIUse(nName) ? nName : oName
}; };
// 不支持的 API 列表 // 不支持的 API 列表
...@@ -978,96 +1016,96 @@ var eventApi = /*#__PURE__*/Object.freeze({ ...@@ -978,96 +1016,96 @@ var eventApi = /*#__PURE__*/Object.freeze({
$emit: $emit $emit: $emit
}); });
function createMediaQueryObserver () { function createMediaQueryObserver () {
const mediaQueryObserver = {}; const mediaQueryObserver = {};
const { const {
windowWidth, windowWidth,
windowHeight windowHeight
} = tt.getSystemInfoSync(); } = tt.getSystemInfoSync();
const orientation = windowWidth < windowHeight ? 'portrait' : 'landscape'; const orientation = windowWidth < windowHeight ? 'portrait' : 'landscape';
mediaQueryObserver.observe = (options, callback) => { mediaQueryObserver.observe = (options, callback) => {
let matches = true; let matches = true;
for (const item in options) { for (const item in options) {
const itemValue = item === 'orientation' ? options[item] : Number(options[item]); const itemValue = item === 'orientation' ? options[item] : Number(options[item]);
if (options[item] !== '') { if (options[item] !== '') {
if (item === 'width') { if (item === 'width') {
if (itemValue === windowWidth) { if (itemValue === windowWidth) {
matches = true; matches = true;
} else { } else {
matches = false; matches = false;
callback(matches); callback(matches);
return matches return matches
} }
} }
if (item === 'minWidth') { if (item === 'minWidth') {
if (windowWidth >= itemValue) { if (windowWidth >= itemValue) {
matches = true; matches = true;
} else { } else {
matches = false; matches = false;
callback(matches); callback(matches);
return matches return matches
} }
} }
if (item === 'maxWidth') { if (item === 'maxWidth') {
if (windowWidth <= itemValue) { if (windowWidth <= itemValue) {
matches = true; matches = true;
} else { } else {
matches = false; matches = false;
callback(matches); callback(matches);
return matches return matches
} }
} }
if (item === 'height') { if (item === 'height') {
if (itemValue === windowHeight) { if (itemValue === windowHeight) {
matches = true; matches = true;
} else { } else {
matches = false; matches = false;
callback(matches); callback(matches);
return matches return matches
} }
} }
if (item === 'minHeight') { if (item === 'minHeight') {
if (windowHeight >= itemValue) { if (windowHeight >= itemValue) {
matches = true; matches = true;
} else { } else {
matches = false; matches = false;
callback(matches); callback(matches);
return matches return matches
} }
} }
if (item === 'maxHeight') { if (item === 'maxHeight') {
if (windowHeight <= itemValue) { if (windowHeight <= itemValue) {
matches = true; matches = true;
} else { } else {
matches = false; matches = false;
callback(matches); callback(matches);
return matches return matches
} }
} }
if (item === 'orientation') { if (item === 'orientation') {
if (options[item] === orientation) { if (options[item] === orientation) {
matches = true; matches = true;
} else { } else {
matches = false; matches = false;
callback(matches); callback(matches);
return matches return matches
} }
} }
} }
} }
callback(matches); callback(matches);
return matches return matches
}; };
mediaQueryObserver.disconnect = () => { mediaQueryObserver.disconnect = () => {
}; };
return mediaQueryObserver return mediaQueryObserver
} }
var api = /*#__PURE__*/Object.freeze({ var api = /*#__PURE__*/Object.freeze({
...@@ -1665,6 +1703,51 @@ function handleEvent (event) { ...@@ -1665,6 +1703,51 @@ function handleEvent (event) {
} }
} }
let locale;
{
locale = tt.getSystemInfoSync().language;
}
const i18n = initVueI18n(locale, {});
const t = i18n.t;
const i18nMixin = i18n.mixin = {
beforeCreate () {
const unwatch = i18n.i18n.watchLocale(() => {
this.$forceUpdate();
});
this.$once('hook:beforeDestroy', function () {
unwatch();
});
},
methods: {
$$t (key, values) {
return t(key, values)
}
}
};
const setLocale$1 = i18n.setLocale;
const getLocale$1 = i18n.getLocale;
function initAppLocale (Vue, appVm, locale) {
const state = Vue.observable({
locale: locale || i18n.getLocale()
});
const localeWatchers = [];
appVm.$watchLocale = (fn) => {
localeWatchers.push(fn);
};
Object.defineProperty(appVm, '$locale', {
get () {
return state.locale
},
set (v) {
state.locale = v;
localeWatchers.forEach(watch => watch(v));
}
});
}
const hooks = [ const hooks = [
'onShow', 'onShow',
'onHide', 'onHide',
...@@ -1821,6 +1904,8 @@ function parseBaseApp (vm, { ...@@ -1821,6 +1904,8 @@ function parseBaseApp (vm, {
}); });
} }
initAppLocale(Vue, vm, tt.getSystemInfoSync().language || 'zh-Hans');
initHooks(appOptions, hooks); initHooks(appOptions, hooks);
return appOptions return appOptions
...@@ -2301,23 +2386,23 @@ function createSubpackageApp (vm) { ...@@ -2301,23 +2386,23 @@ function createSubpackageApp (vm) {
return vm return vm
} }
function createPlugin (vm) { function createPlugin (vm) {
const appOptions = parseApp(vm); const appOptions = parseApp(vm);
if (isFn(appOptions.onShow) && tt.onAppShow) { if (isFn(appOptions.onShow) && tt.onAppShow) {
tt.onAppShow((...args) => { tt.onAppShow((...args) => {
appOptions.onShow.apply(vm, args); appOptions.onShow.apply(vm, args);
}); });
} }
if (isFn(appOptions.onHide) && tt.onAppHide) { if (isFn(appOptions.onHide) && tt.onAppHide) {
tt.onAppHide((...args) => { tt.onAppHide((...args) => {
appOptions.onHide.apply(vm, args); appOptions.onHide.apply(vm, args);
}); });
} }
if (isFn(appOptions.onLaunch)) { if (isFn(appOptions.onLaunch)) {
const args = tt.getLaunchOptionsSync && tt.getLaunchOptionsSync(); const args = tt.getLaunchOptionsSync && tt.getLaunchOptionsSync();
appOptions.onLaunch.call(vm, args); appOptions.onLaunch.call(vm, args);
} }
return vm return vm
} }
todos.forEach(todoApi => { todos.forEach(todoApi => {
......
import Vue from 'vue'; import Vue from 'vue';
import { initVueI18n } from '@dcloudio/uni-i18n';
function b64DecodeUnicode (str) { function b64DecodeUnicode (str) {
return decodeURIComponent(atob(str).split('').map(function (c) { return decodeURIComponent(atob(str).split('').map(function (c) {
...@@ -192,7 +193,7 @@ function queue (hooks, data) { ...@@ -192,7 +193,7 @@ function queue (hooks, data) {
} }
if (res === false) { if (res === false) {
return { return {
then () {} then () { }
} }
} }
} }
...@@ -240,15 +241,15 @@ function getApiInterceptorHooks (method) { ...@@ -240,15 +241,15 @@ function getApiInterceptorHooks (method) {
if (hook !== 'returnValue') { if (hook !== 'returnValue') {
interceptor[hook] = globalInterceptors[hook].slice(); interceptor[hook] = globalInterceptors[hook].slice();
} }
}); });
const scopedInterceptor = scopedInterceptors[method]; const scopedInterceptor = scopedInterceptors[method];
if (scopedInterceptor) { if (scopedInterceptor) {
Object.keys(scopedInterceptor).forEach(hook => { Object.keys(scopedInterceptor).forEach(hook => {
if (hook !== 'returnValue') { if (hook !== 'returnValue') {
interceptor[hook] = (interceptor[hook] || []).concat(scopedInterceptor[hook]); interceptor[hook] = (interceptor[hook] || []).concat(scopedInterceptor[hook]);
} }
}); });
} }
return interceptor return interceptor
} }
...@@ -272,16 +273,20 @@ const promiseInterceptor = { ...@@ -272,16 +273,20 @@ const promiseInterceptor = {
if (!isPromise(res)) { if (!isPromise(res)) {
return res return res
} }
return res.then(res => { return new Promise((resolve, reject) => {
return res[1] res.then(res => {
}).catch(res => { if (res[0]) {
return res[0] reject(res[0]);
} else {
resolve(res[1]);
}
});
}) })
} }
}; };
const SYNC_API_RE = const SYNC_API_RE =
/^\$|Window$|WindowStyle$|sendNativeEvent|restoreGlobal|getCurrentSubNVue|getMenuButtonBoundingClientRect|^report|interceptors|Interceptor$|getSubNVueById|requireNativePlugin|upx2px|hideKeyboard|canIUse|^create|Sync$|Manager$|base64ToArrayBuffer|arrayBufferToBase64/; /^\$|Window$|WindowStyle$|sendNativeEvent|restoreGlobal|getCurrentSubNVue|getMenuButtonBoundingClientRect|^report|interceptors|Interceptor$|getSubNVueById|requireNativePlugin|upx2px|hideKeyboard|canIUse|^create|Sync$|Manager$|base64ToArrayBuffer|arrayBufferToBase64|getLocale|setLocale/;
const CONTEXT_API_RE = /^create|Manager$/; const CONTEXT_API_RE = /^create|Manager$/;
...@@ -394,6 +399,40 @@ function upx2px (number, newDeviceWidth) { ...@@ -394,6 +399,40 @@ function upx2px (number, newDeviceWidth) {
return number < 0 ? -result : result return number < 0 ? -result : result
} }
function getLocale () {
// 优先使用 $locale
const app = getApp({
allowDefault: true
});
if (app && app.$vm) {
return app.$vm.$locale
}
return wx.getSystemInfoSync().language || 'zh-Hans'
}
function setLocale (locale) {
const app = getApp();
if (!app) {
return false
}
const oldLocale = app.$vm.$locale;
if (oldLocale !== locale) {
app.$vm.$locale = locale;
onLocaleChangeCallbacks.forEach((fn) => fn({
locale
}));
return true
}
return false
}
const onLocaleChangeCallbacks = [];
function onLocaleChange (fn) {
if (onLocaleChangeCallbacks.indexOf(fn) === -1) {
onLocaleChangeCallbacks.push(fn);
}
}
const interceptors = { const interceptors = {
promiseInterceptor promiseInterceptor
}; };
...@@ -401,6 +440,9 @@ const interceptors = { ...@@ -401,6 +440,9 @@ const interceptors = {
var baseApi = /*#__PURE__*/Object.freeze({ var baseApi = /*#__PURE__*/Object.freeze({
__proto__: null, __proto__: null,
upx2px: upx2px, upx2px: upx2px,
getLocale: getLocale,
setLocale: setLocale,
onLocaleChange: onLocaleChange,
addInterceptor: addInterceptor, addInterceptor: addInterceptor,
removeInterceptor: removeInterceptor, removeInterceptor: removeInterceptor,
interceptors: interceptors interceptors: interceptors
...@@ -731,7 +773,7 @@ function initTriggerEvent (mpInstance) { ...@@ -731,7 +773,7 @@ function initTriggerEvent (mpInstance) {
}; };
} }
function initHook (name, options) { function initHook (name, options, isComponent) {
const oldHook = options[name]; const oldHook = options[name];
if (!oldHook) { if (!oldHook) {
options[name] = function () { options[name] = function () {
...@@ -1301,6 +1343,51 @@ function handleEvent (event) { ...@@ -1301,6 +1343,51 @@ function handleEvent (event) {
} }
} }
let locale;
{
locale = wx.getSystemInfoSync().language;
}
const i18n = initVueI18n(locale, {});
const t = i18n.t;
const i18nMixin = i18n.mixin = {
beforeCreate () {
const unwatch = i18n.i18n.watchLocale(() => {
this.$forceUpdate();
});
this.$once('hook:beforeDestroy', function () {
unwatch();
});
},
methods: {
$$t (key, values) {
return t(key, values)
}
}
};
const setLocale$1 = i18n.setLocale;
const getLocale$1 = i18n.getLocale;
function initAppLocale (Vue, appVm, locale) {
const state = Vue.observable({
locale: locale || i18n.getLocale()
});
const localeWatchers = [];
appVm.$watchLocale = (fn) => {
localeWatchers.push(fn);
};
Object.defineProperty(appVm, '$locale', {
get () {
return state.locale
},
set (v) {
state.locale = v;
localeWatchers.forEach(watch => watch(v));
}
});
}
const eventChannels = {}; const eventChannels = {};
const eventChannelStack = []; const eventChannelStack = [];
...@@ -1475,6 +1562,8 @@ function parseBaseApp (vm, { ...@@ -1475,6 +1562,8 @@ function parseBaseApp (vm, {
}); });
} }
initAppLocale(Vue, vm, wx.getSystemInfoSync().language || 'zh-Hans');
initHooks(appOptions, hooks); initHooks(appOptions, hooks);
return appOptions return appOptions
......
import Vue from 'vue'; import Vue from 'vue';
import { initVueI18n } from '@dcloudio/uni-i18n';
function b64DecodeUnicode (str) { function b64DecodeUnicode (str) {
return decodeURIComponent(atob(str).split('').map(function (c) { return decodeURIComponent(atob(str).split('').map(function (c) {
...@@ -192,7 +193,7 @@ function queue (hooks, data) { ...@@ -192,7 +193,7 @@ function queue (hooks, data) {
} }
if (res === false) { if (res === false) {
return { return {
then () {} then () { }
} }
} }
} }
...@@ -240,15 +241,15 @@ function getApiInterceptorHooks (method) { ...@@ -240,15 +241,15 @@ function getApiInterceptorHooks (method) {
if (hook !== 'returnValue') { if (hook !== 'returnValue') {
interceptor[hook] = globalInterceptors[hook].slice(); interceptor[hook] = globalInterceptors[hook].slice();
} }
}); });
const scopedInterceptor = scopedInterceptors[method]; const scopedInterceptor = scopedInterceptors[method];
if (scopedInterceptor) { if (scopedInterceptor) {
Object.keys(scopedInterceptor).forEach(hook => { Object.keys(scopedInterceptor).forEach(hook => {
if (hook !== 'returnValue') { if (hook !== 'returnValue') {
interceptor[hook] = (interceptor[hook] || []).concat(scopedInterceptor[hook]); interceptor[hook] = (interceptor[hook] || []).concat(scopedInterceptor[hook]);
} }
}); });
} }
return interceptor return interceptor
} }
...@@ -272,16 +273,20 @@ const promiseInterceptor = { ...@@ -272,16 +273,20 @@ const promiseInterceptor = {
if (!isPromise(res)) { if (!isPromise(res)) {
return res return res
} }
return res.then(res => { return new Promise((resolve, reject) => {
return res[1] res.then(res => {
}).catch(res => { if (res[0]) {
return res[0] reject(res[0]);
} else {
resolve(res[1]);
}
});
}) })
} }
}; };
const SYNC_API_RE = const SYNC_API_RE =
/^\$|Window$|WindowStyle$|sendNativeEvent|restoreGlobal|getCurrentSubNVue|getMenuButtonBoundingClientRect|^report|interceptors|Interceptor$|getSubNVueById|requireNativePlugin|upx2px|hideKeyboard|canIUse|^create|Sync$|Manager$|base64ToArrayBuffer|arrayBufferToBase64/; /^\$|Window$|WindowStyle$|sendNativeEvent|restoreGlobal|getCurrentSubNVue|getMenuButtonBoundingClientRect|^report|interceptors|Interceptor$|getSubNVueById|requireNativePlugin|upx2px|hideKeyboard|canIUse|^create|Sync$|Manager$|base64ToArrayBuffer|arrayBufferToBase64|getLocale|setLocale/;
const CONTEXT_API_RE = /^create|Manager$/; const CONTEXT_API_RE = /^create|Manager$/;
...@@ -394,6 +399,40 @@ function upx2px (number, newDeviceWidth) { ...@@ -394,6 +399,40 @@ function upx2px (number, newDeviceWidth) {
return number < 0 ? -result : result return number < 0 ? -result : result
} }
function getLocale () {
// 优先使用 $locale
const app = getApp({
allowDefault: true
});
if (app && app.$vm) {
return app.$vm.$locale
}
return qa.getSystemInfoSync().language || 'zh-Hans'
}
function setLocale (locale) {
const app = getApp();
if (!app) {
return false
}
const oldLocale = app.$vm.$locale;
if (oldLocale !== locale) {
app.$vm.$locale = locale;
onLocaleChangeCallbacks.forEach((fn) => fn({
locale
}));
return true
}
return false
}
const onLocaleChangeCallbacks = [];
function onLocaleChange (fn) {
if (onLocaleChangeCallbacks.indexOf(fn) === -1) {
onLocaleChangeCallbacks.push(fn);
}
}
const interceptors = { const interceptors = {
promiseInterceptor promiseInterceptor
}; };
...@@ -401,6 +440,9 @@ const interceptors = { ...@@ -401,6 +440,9 @@ const interceptors = {
var baseApi = /*#__PURE__*/Object.freeze({ var baseApi = /*#__PURE__*/Object.freeze({
__proto__: null, __proto__: null,
upx2px: upx2px, upx2px: upx2px,
getLocale: getLocale,
setLocale: setLocale,
onLocaleChange: onLocaleChange,
addInterceptor: addInterceptor, addInterceptor: addInterceptor,
removeInterceptor: removeInterceptor, removeInterceptor: removeInterceptor,
interceptors: interceptors interceptors: interceptors
...@@ -801,7 +843,7 @@ function initTriggerEvent (mpInstance) { ...@@ -801,7 +843,7 @@ function initTriggerEvent (mpInstance) {
}; };
} }
function initHook (name, options) { function initHook (name, options, isComponent) {
const oldHook = options[name]; const oldHook = options[name];
if (!oldHook) { if (!oldHook) {
options[name] = function () { options[name] = function () {
...@@ -1371,6 +1413,51 @@ function handleEvent (event) { ...@@ -1371,6 +1413,51 @@ function handleEvent (event) {
} }
} }
let locale;
{
locale = qa.getSystemInfoSync().language;
}
const i18n = initVueI18n(locale, {});
const t = i18n.t;
const i18nMixin = i18n.mixin = {
beforeCreate () {
const unwatch = i18n.i18n.watchLocale(() => {
this.$forceUpdate();
});
this.$once('hook:beforeDestroy', function () {
unwatch();
});
},
methods: {
$$t (key, values) {
return t(key, values)
}
}
};
const setLocale$1 = i18n.setLocale;
const getLocale$1 = i18n.getLocale;
function initAppLocale (Vue, appVm, locale) {
const state = Vue.observable({
locale: locale || i18n.getLocale()
});
const localeWatchers = [];
appVm.$watchLocale = (fn) => {
localeWatchers.push(fn);
};
Object.defineProperty(appVm, '$locale', {
get () {
return state.locale
},
set (v) {
state.locale = v;
localeWatchers.forEach(watch => watch(v));
}
});
}
const hooks = [ const hooks = [
'onShow', 'onShow',
'onHide', 'onHide',
...@@ -1472,6 +1559,8 @@ function parseBaseApp (vm, { ...@@ -1472,6 +1559,8 @@ function parseBaseApp (vm, {
}); });
} }
initAppLocale(Vue, vm, qa.getSystemInfoSync().language || 'zh-Hans');
initHooks(appOptions, hooks); initHooks(appOptions, hooks);
return appOptions return appOptions
......
...@@ -25,7 +25,7 @@ if (__PLATFORM__ === 'h5') { ...@@ -25,7 +25,7 @@ if (__PLATFORM__ === 'h5') {
locale = weex.requireModule('plus').getLanguage() locale = weex.requireModule('plus').getLanguage()
} }
} else { } else {
locale = uni.getSystemInfoSync().language locale = __GLOBAL__.getSystemInfoSync().language
} }
export const i18n = initVueI18n(locale, __PLATFORM__ === 'app-plus' || __PLATFORM__ === 'h5' ? messages : {}) export const i18n = initVueI18n(locale, __PLATFORM__ === 'app-plus' || __PLATFORM__ === 'h5' ? messages : {})
...@@ -48,9 +48,9 @@ export const i18nMixin = i18n.mixin = { ...@@ -48,9 +48,9 @@ export const i18nMixin = i18n.mixin = {
export const setLocale = i18n.setLocale export const setLocale = i18n.setLocale
export const getLocale = i18n.getLocale export const getLocale = i18n.getLocale
export function initAppLocale (Vue, appVm) { export function initAppLocale (Vue, appVm, locale) {
const state = Vue.observable({ const state = Vue.observable({
locale: i18n.getLocale() locale: locale || i18n.getLocale()
}) })
const localeWatchers = [] const localeWatchers = []
appVm.$watchLocale = (fn) => { appVm.$watchLocale = (fn) => {
......
...@@ -3,4 +3,6 @@ export { ...@@ -3,4 +3,6 @@ export {
} }
from './upx2px' from './upx2px'
export * from './locale'
export * from '../service/api/base/interceptor' export * from '../service/api/base/interceptor'
export function getLocale () {
// 优先使用 $locale
const app = getApp({
allowDefault: true
})
if (app && app.$vm) {
return app.$vm.$locale
}
return __GLOBAL__.getSystemInfoSync().language || 'zh-Hans'
}
export function setLocale (locale) {
const app = getApp()
if (!app) {
return false
}
const oldLocale = app.$vm.$locale
if (oldLocale !== locale) {
app.$vm.$locale = locale
onLocaleChangeCallbacks.forEach((fn) => fn({
locale
}))
return true
}
return false
}
const onLocaleChangeCallbacks = []
export function onLocaleChange (fn) {
if (onLocaleChangeCallbacks.indexOf(fn) === -1) {
onLocaleChangeCallbacks.push(fn)
}
}
...@@ -5,6 +5,10 @@ import { ...@@ -5,6 +5,10 @@ import {
initMocks initMocks
} from 'uni-wrapper/util' } from 'uni-wrapper/util'
import {
initAppLocale
} from 'uni-helpers/i18n/index'
import EventChannel from 'uni-helpers/EventChannel' import EventChannel from 'uni-helpers/EventChannel'
import { import {
...@@ -102,7 +106,8 @@ export default function parseBaseApp (vm, { ...@@ -102,7 +106,8 @@ export default function parseBaseApp (vm, {
initRefs initRefs
}) { }) {
initEventChannel() initEventChannel()
if (__PLATFORM__ === 'mp-weixin' || __PLATFORM__ === 'mp-qq' || __PLATFORM__ === 'mp-toutiao' || __PLATFORM__ === 'mp-kuaishou' || __PLATFORM__ === 'mp-alipay' || __PLATFORM__ === 'mp-baidu') { if (__PLATFORM__ === 'mp-weixin' || __PLATFORM__ === 'mp-qq' || __PLATFORM__ === 'mp-toutiao' || __PLATFORM__ ===
'mp-kuaishou' || __PLATFORM__ === 'mp-alipay' || __PLATFORM__ === 'mp-baidu') {
initScopedSlotsParams() initScopedSlotsParams()
} }
if (vm.$options.store) { if (vm.$options.store) {
...@@ -180,7 +185,9 @@ export default function parseBaseApp (vm, { ...@@ -180,7 +185,9 @@ export default function parseBaseApp (vm, {
}) })
} }
initAppLocale(Vue, vm, __GLOBAL__.getSystemInfoSync().language || 'zh-Hans')
initHooks(appOptions, hooks) initHooks(appOptions, hooks)
return appOptions return appOptions
} }
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册