From f55c7d586e9bd9cac60f0e0d54f28271a2bef169 Mon Sep 17 00:00:00 2001 From: fxy060608 Date: Tue, 22 Feb 2022 19:58:36 +0800 Subject: [PATCH] refactor: uni.onAppLaunch => uni.onCreateVueApp --- packages/uni-api/src/index.ts | 2 + packages/uni-api/src/service/lifecycle/app.ts | 39 +- .../uni-app-plus/dist/uni-app-service.es.js | 498 +++++++++--------- .../uni-app-plus/src/service/api/index.ts | 2 +- .../service/framework/app/initAppLaunch.ts | 19 +- .../src/service/framework/app/utils.ts | 10 +- packages/uni-h5-vite/lib/api.json | 2 +- packages/uni-h5/dist/uni-h5.cjs.js | 283 +++++----- packages/uni-h5/dist/uni-h5.es.js | 331 ++++++------ packages/uni-h5/src/framework/setup/index.ts | 17 +- packages/uni-h5/src/framework/setup/utils.ts | 10 +- packages/uni-h5/src/service/api/index.ts | 2 +- packages/uni-mp-alipay/dist/uni.api.esm.js | 34 +- packages/uni-mp-alipay/dist/uni.mp.esm.js | 12 +- packages/uni-mp-baidu/dist/uni.api.esm.js | 34 +- packages/uni-mp-baidu/dist/uni.mp.esm.js | 12 +- packages/uni-mp-core/src/api/hook.ts | 19 - packages/uni-mp-core/src/api/index.ts | 7 +- packages/uni-mp-core/src/runtime/app.ts | 10 +- packages/uni-mp-kuaishou/dist/uni.api.esm.js | 34 +- packages/uni-mp-kuaishou/dist/uni.mp.esm.js | 12 +- packages/uni-mp-lark/dist/uni.api.esm.js | 34 +- packages/uni-mp-lark/dist/uni.mp.esm.js | 12 +- packages/uni-mp-qq/dist/uni.api.esm.js | 34 +- packages/uni-mp-qq/dist/uni.mp.esm.js | 12 +- packages/uni-mp-toutiao/dist/uni.api.esm.js | 34 +- packages/uni-mp-toutiao/dist/uni.mp.esm.js | 12 +- packages/uni-mp-vue/dist/vue.runtime.esm.js | 3 + packages/uni-mp-weixin/dist/uni.api.esm.js | 34 +- packages/uni-mp-weixin/dist/uni.mp.esm.js | 12 +- .../uni-quickapp-webview/dist/uni.api.esm.js | 34 +- .../uni-quickapp-webview/dist/uni.mp.esm.js | 12 +- packages/uni-stat/dist/uni-stat.cjs.js | 6 +- packages/uni-stat/dist/uni-stat.es.js | 33 +- packages/uni-stat/src/index.js | 6 +- packages/uni-vue/src/index.ts | 8 + packages/uni-vue/src/onCreateVueApp.ts | 21 + 37 files changed, 854 insertions(+), 842 deletions(-) delete mode 100644 packages/uni-mp-core/src/api/hook.ts create mode 100644 packages/uni-vue/src/onCreateVueApp.ts diff --git a/packages/uni-api/src/index.ts b/packages/uni-api/src/index.ts index 438dd1296..8b80b72a6 100644 --- a/packages/uni-api/src/index.ts +++ b/packages/uni-api/src/index.ts @@ -103,6 +103,8 @@ export * from './protocols/ad/fullScreenVideoAd' export * from './protocols/ad/interstitialAd' export * from './protocols/ad/interactiveAd' +export { onCreateVueApp } from '@dcloudio/uni-vue' + // helpers export { defineOnApi, diff --git a/packages/uni-api/src/service/lifecycle/app.ts b/packages/uni-api/src/service/lifecycle/app.ts index 09f6c35bb..e5c664e89 100644 --- a/packages/uni-api/src/service/lifecycle/app.ts +++ b/packages/uni-api/src/service/lifecycle/app.ts @@ -1,22 +1,43 @@ import { getEnterOptions, getLaunchOptions } from '@dcloudio/uni-platform' -import { ON_LAUNCH } from '@dcloudio/uni-shared' +import { ON_HIDE, ON_SHOW } from '@dcloudio/uni-shared' import { defineSyncApi } from '../../helpers/api' import { ComponentInternalInstance, injectHook } from 'vue' -type AppLaunchHook = (options: UniApp.LaunchOptionsApp) => void -const appLaunchHooks: AppLaunchHook[] = [] -export function onAppLaunch(hook: AppLaunchHook) { +type AppShowHook = (options: UniApp.LaunchOptionsApp) => void +type AppHideHook = () => void +interface AppHooks { + onShow: AppShowHook[] + onHide: AppHideHook[] +} + +const appHooks: AppHooks = { + [ON_SHOW]: [], + [ON_HIDE]: [], +} + +function onAppHook(type: keyof AppHooks, hook: (...args: any[]) => void) { const app = getApp({ allowDefault: true }) if (app && app.$vm) { - return injectHook(ON_LAUNCH, hook, app.$vm.$) + return injectHook(type, hook, app.$vm.$) } - appLaunchHooks.push(hook) + appHooks[type].push(hook) +} + +export function onAppShow(hook: AppShowHook) { + onAppHook(ON_SHOW, hook) +} + +export function onAppHide(hook: AppHideHook) { + onAppHook(ON_HIDE, hook) } -export function injectAppLaunchHooks(appInstance: ComponentInternalInstance) { - appLaunchHooks.forEach((hook) => { - injectHook(ON_LAUNCH, hook, appInstance) +export function injectAppHooks( + type: keyof AppHooks, + appInstance: ComponentInternalInstance +) { + appHooks[type].forEach((hook) => { + injectHook(type, hook, appInstance) }) } diff --git a/packages/uni-app-plus/dist/uni-app-service.es.js b/packages/uni-app-plus/dist/uni-app-service.es.js index 1f573bd5f..2ab4ddad4 100644 --- a/packages/uni-app-plus/dist/uni-app-service.es.js +++ b/packages/uni-app-plus/dist/uni-app-service.es.js @@ -2890,10 +2890,10 @@ var serviceContext = (function (vue) { const enterOptions = createLaunchOptions(); const launchOptions = createLaunchOptions(); function getLaunchOptions() { - return launchOptions; + return extend({}, launchOptions); } function getEnterOptions() { - return enterOptions; + return extend({}, enterOptions); } function initEnterOptions({ path, query, referrerInfo, }) { extend(enterOptions, { @@ -2909,7 +2909,7 @@ var serviceContext = (function (vue) { referrerInfo: referrerInfo || {}, }); extend(enterOptions, launchOptions); - return launchOptions; + return extend({}, launchOptions); } function parseRedirectInfo() { const weexPlus = weex.requireModule('plus'); @@ -11634,19 +11634,10 @@ var serviceContext = (function (vue) { }); }); - const appLaunchHooks = []; - function onAppLaunch(hook) { - const app = getApp({ allowDefault: true }); - if (app && app.$vm) { - return vue.injectHook(ON_LAUNCH, hook, app.$vm.$); - } - appLaunchHooks.push(hook); - } - function injectAppLaunchHooks(appInstance) { - appLaunchHooks.forEach((hook) => { - vue.injectHook(ON_LAUNCH, hook, appInstance); - }); - } + ({ + [ON_SHOW]: [], + [ON_HIDE]: [], + }); const API_GET_ENTER_OPTIONS_SYNC = 'getEnterOptionsSync'; const getEnterOptionsSync = defineSyncApi(API_GET_ENTER_OPTIONS_SYNC, () => { return getEnterOptions(); @@ -13174,6 +13165,249 @@ var serviceContext = (function (vue) { }, }; + function injectLifecycleHook(name, hook, publicThis, instance) { + if (isFunction(hook)) { + vue.injectHook(name, hook.bind(publicThis), instance); + } + } + function initHooks(options, instance, publicThis) { + const mpType = options.mpType || publicThis.$mpType; + // 为了组件也可以监听部分生命周期,故不再判断mpType,统一添加on开头的生命周期 + Object.keys(options).forEach((name) => { + if (name.indexOf('on') === 0) { + const hooks = options[name]; + if (isArray$1(hooks)) { + hooks.forEach((hook) => injectLifecycleHook(name, hook, publicThis, instance)); + } + else { + injectLifecycleHook(name, hooks, publicThis, instance); + } + } + }); + if (mpType === 'page') { + instance.__isVisible = true; + try { + invokeHook(publicThis, ON_LOAD, instance.attrs.__pageQuery); + delete instance.attrs.__pageQuery; + } + catch (e) { + console.error(e.message + LINEFEED + e.stack); + } + vue.nextTick(() => { + // 延迟onShow,保证组件的onShow也可以监听到 + invokeHook(publicThis, ON_SHOW); + }); + } + } + + function initRenderjs(options, instance) { + initModules(instance, options.$renderjs, options['$' + RENDERJS_MODULES]); + } + function initModules(instance, modules, moduleIds = {}) { + if (!isArray$1(modules)) { + return; + } + const ownerId = instance.uid; + // 在vue的定制内核中,通过$wxsModules来判断事件函数源码中是否包含该模块调用 + // !$wxsModules.find(module => invokerSourceCode.indexOf('.' + module + '.') > -1) + const $wxsModules = (instance.$wxsModules || + (instance.$wxsModules = [])); + const ctx = instance.ctx; + modules.forEach((module) => { + if (moduleIds[module]) { + ctx[module] = proxyModule(ownerId, moduleIds[module], module); + $wxsModules.push(module); + } + else { + if ((process.env.NODE_ENV !== 'production')) { + console.error(formatLog('initModules', modules, moduleIds)); + } + } + }); + } + function proxyModule(ownerId, moduleId, module) { + const target = {}; + return new Proxy(target, { + get(_, p) { + return (target[p] || + (target[p] = createModuleFunction(ownerId, moduleId, module, p))); + }, + }); + } + function createModuleFunction(ownerId, moduleId, module, name) { + const target = () => { }; + const toJSON = () => WXS_PROTOCOL + JSON.stringify([ownerId, moduleId, module + '.' + name]); + return new Proxy(target, { + get(_, p) { + if (p === 'toJSON') { + return toJSON; + } + return (target[p] || + (target[p] = createModuleFunction(ownerId, moduleId, module + '.' + name, p))); + }, + apply(_target, _thisArg, args) { + return (WXS_PROTOCOL + + JSON.stringify([ownerId, moduleId, module + '.' + name, [...args]])); + }, + }); + } + + function initWxs(options, instance) { + initModules(instance, options.$wxs, options['$' + WXS_MODULES]); + } + + function applyOptions(options, instance, publicThis) { + { + initWxs(options, instance); + initRenderjs(options, instance); + } + initHooks(options, instance, publicThis); + } + + function set(target, key, val) { + return (target[key] = val); + } + + function errorHandler(err, instance, info) { + if (!instance) { + throw err; + } + const app = getApp(); + if (!app || !app.$vm) { + throw err; + } + { + invokeHook(app.$vm, ON_ERROR, err); + } + } + function mergeAsArray(to, from) { + return to ? [...new Set([].concat(to, from))] : from; + } + function initOptionMergeStrategies(optionMergeStrategies) { + UniLifecycleHooks.forEach((name) => { + optionMergeStrategies[name] = mergeAsArray; + }); + } + + let realAtob; + const b64 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/='; + const b64re = /^(?:[A-Za-z\d+/]{4})*?(?:[A-Za-z\d+/]{2}(?:==)?|[A-Za-z\d+/]{3}=?)?$/; + if (typeof atob !== 'function') { + realAtob = function (str) { + str = String(str).replace(/[\t\n\f\r ]+/g, ''); + if (!b64re.test(str)) { + throw new Error("Failed to execute 'atob' on 'Window': The string to be decoded is not correctly encoded."); + } + // Adding the padding if missing, for semplicity + str += '=='.slice(2 - (str.length & 3)); + var bitmap; + var result = ''; + var r1; + var r2; + var i = 0; + for (; i < str.length;) { + bitmap = + (b64.indexOf(str.charAt(i++)) << 18) | + (b64.indexOf(str.charAt(i++)) << 12) | + ((r1 = b64.indexOf(str.charAt(i++))) << 6) | + (r2 = b64.indexOf(str.charAt(i++))); + result += + r1 === 64 + ? String.fromCharCode((bitmap >> 16) & 255) + : r2 === 64 + ? String.fromCharCode((bitmap >> 16) & 255, (bitmap >> 8) & 255) + : String.fromCharCode((bitmap >> 16) & 255, (bitmap >> 8) & 255, bitmap & 255); + } + return result; + }; + } + else { + // 注意atob只能在全局对象上调用,例如:`const Base64 = {atob};Base64.atob('xxxx')`是错误的用法 + realAtob = atob; + } + function b64DecodeUnicode(str) { + return decodeURIComponent(realAtob(str) + .split('') + .map(function (c) { + return '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2); + }) + .join('')); + } + function getCurrentUserInfo() { + const token = uni.getStorageSync('uni_id_token') || ''; + const tokenArr = token.split('.'); + if (!token || tokenArr.length !== 3) { + return { + uid: null, + role: [], + permission: [], + tokenExpired: 0, + }; + } + let userInfo; + try { + userInfo = JSON.parse(b64DecodeUnicode(tokenArr[1])); + } + catch (error) { + throw new Error('获取当前用户信息出错,详细错误信息为:' + error.message); + } + userInfo.tokenExpired = userInfo.exp * 1000; + delete userInfo.exp; + delete userInfo.iat; + return userInfo; + } + function uniIdMixin(globalProperties) { + globalProperties.uniIDHasRole = function (roleId) { + const { role } = getCurrentUserInfo(); + return role.indexOf(roleId) > -1; + }; + globalProperties.uniIDHasPermission = function (permissionId) { + const { permission } = getCurrentUserInfo(); + return this.uniIDHasRole('admin') || permission.indexOf(permissionId) > -1; + }; + globalProperties.uniIDTokenValid = function () { + const { tokenExpired } = getCurrentUserInfo(); + return tokenExpired > Date.now(); + }; + } + + let vueApp$1; + const createVueAppHooks = []; + /** + * 提供 createApp 的回调事件,方便三方插件接收 App 对象,处理挂靠全局 mixin 之类的逻辑 + * @param hook + */ + function onCreateVueApp(hook) { + // TODO 每个 nvue 页面都会触发 + if (vueApp$1) { + return hook(vueApp$1); + } + createVueAppHooks.push(hook); + } + function invokeCreateVueAppHook(app) { + vueApp$1 = app; + createVueAppHooks.forEach((hook) => hook(app)); + } + + function initApp(app) { + const appConfig = app._context.config; + if (isFunction(app._component.onError)) { + appConfig.errorHandler = errorHandler; + } + initOptionMergeStrategies(appConfig.optionMergeStrategies); + const globalProperties = appConfig.globalProperties; + { + uniIdMixin(globalProperties); + } + { + globalProperties.$set = set; + globalProperties.$applyOptions = applyOptions; + } + { + invokeCreateVueAppHook(app); + } + } + function warpPlusSuccessCallback(resolve, after) { return function successCallback(data) { delete data.code; @@ -17122,228 +17356,6 @@ var serviceContext = (function (vue) { }, errorCallback); }, RequestPaymentProtocol); - function injectLifecycleHook(name, hook, publicThis, instance) { - if (isFunction(hook)) { - vue.injectHook(name, hook.bind(publicThis), instance); - } - } - function initHooks(options, instance, publicThis) { - const mpType = options.mpType || publicThis.$mpType; - // 为了组件也可以监听部分生命周期,故不再判断mpType,统一添加on开头的生命周期 - Object.keys(options).forEach((name) => { - if (name.indexOf('on') === 0) { - const hooks = options[name]; - if (isArray$1(hooks)) { - hooks.forEach((hook) => injectLifecycleHook(name, hook, publicThis, instance)); - } - else { - injectLifecycleHook(name, hooks, publicThis, instance); - } - } - }); - if (mpType === 'page') { - instance.__isVisible = true; - try { - invokeHook(publicThis, ON_LOAD, instance.attrs.__pageQuery); - delete instance.attrs.__pageQuery; - } - catch (e) { - console.error(e.message + LINEFEED + e.stack); - } - vue.nextTick(() => { - // 延迟onShow,保证组件的onShow也可以监听到 - invokeHook(publicThis, ON_SHOW); - }); - } - } - - function initRenderjs(options, instance) { - initModules(instance, options.$renderjs, options['$' + RENDERJS_MODULES]); - } - function initModules(instance, modules, moduleIds = {}) { - if (!isArray$1(modules)) { - return; - } - const ownerId = instance.uid; - // 在vue的定制内核中,通过$wxsModules来判断事件函数源码中是否包含该模块调用 - // !$wxsModules.find(module => invokerSourceCode.indexOf('.' + module + '.') > -1) - const $wxsModules = (instance.$wxsModules || - (instance.$wxsModules = [])); - const ctx = instance.ctx; - modules.forEach((module) => { - if (moduleIds[module]) { - ctx[module] = proxyModule(ownerId, moduleIds[module], module); - $wxsModules.push(module); - } - else { - if ((process.env.NODE_ENV !== 'production')) { - console.error(formatLog('initModules', modules, moduleIds)); - } - } - }); - } - function proxyModule(ownerId, moduleId, module) { - const target = {}; - return new Proxy(target, { - get(_, p) { - return (target[p] || - (target[p] = createModuleFunction(ownerId, moduleId, module, p))); - }, - }); - } - function createModuleFunction(ownerId, moduleId, module, name) { - const target = () => { }; - const toJSON = () => WXS_PROTOCOL + JSON.stringify([ownerId, moduleId, module + '.' + name]); - return new Proxy(target, { - get(_, p) { - if (p === 'toJSON') { - return toJSON; - } - return (target[p] || - (target[p] = createModuleFunction(ownerId, moduleId, module + '.' + name, p))); - }, - apply(_target, _thisArg, args) { - return (WXS_PROTOCOL + - JSON.stringify([ownerId, moduleId, module + '.' + name, [...args]])); - }, - }); - } - - function initWxs(options, instance) { - initModules(instance, options.$wxs, options['$' + WXS_MODULES]); - } - - function applyOptions(options, instance, publicThis) { - { - initWxs(options, instance); - initRenderjs(options, instance); - } - initHooks(options, instance, publicThis); - } - - function set(target, key, val) { - return (target[key] = val); - } - - function errorHandler(err, instance, info) { - if (!instance) { - throw err; - } - const app = getApp(); - if (!app || !app.$vm) { - throw err; - } - { - invokeHook(app.$vm, ON_ERROR, err); - } - } - function mergeAsArray(to, from) { - return to ? [...new Set([].concat(to, from))] : from; - } - function initOptionMergeStrategies(optionMergeStrategies) { - UniLifecycleHooks.forEach((name) => { - optionMergeStrategies[name] = mergeAsArray; - }); - } - - let realAtob; - const b64 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/='; - const b64re = /^(?:[A-Za-z\d+/]{4})*?(?:[A-Za-z\d+/]{2}(?:==)?|[A-Za-z\d+/]{3}=?)?$/; - if (typeof atob !== 'function') { - realAtob = function (str) { - str = String(str).replace(/[\t\n\f\r ]+/g, ''); - if (!b64re.test(str)) { - throw new Error("Failed to execute 'atob' on 'Window': The string to be decoded is not correctly encoded."); - } - // Adding the padding if missing, for semplicity - str += '=='.slice(2 - (str.length & 3)); - var bitmap; - var result = ''; - var r1; - var r2; - var i = 0; - for (; i < str.length;) { - bitmap = - (b64.indexOf(str.charAt(i++)) << 18) | - (b64.indexOf(str.charAt(i++)) << 12) | - ((r1 = b64.indexOf(str.charAt(i++))) << 6) | - (r2 = b64.indexOf(str.charAt(i++))); - result += - r1 === 64 - ? String.fromCharCode((bitmap >> 16) & 255) - : r2 === 64 - ? String.fromCharCode((bitmap >> 16) & 255, (bitmap >> 8) & 255) - : String.fromCharCode((bitmap >> 16) & 255, (bitmap >> 8) & 255, bitmap & 255); - } - return result; - }; - } - else { - // 注意atob只能在全局对象上调用,例如:`const Base64 = {atob};Base64.atob('xxxx')`是错误的用法 - realAtob = atob; - } - function b64DecodeUnicode(str) { - return decodeURIComponent(realAtob(str) - .split('') - .map(function (c) { - return '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2); - }) - .join('')); - } - function getCurrentUserInfo() { - const token = uni.getStorageSync('uni_id_token') || ''; - const tokenArr = token.split('.'); - if (!token || tokenArr.length !== 3) { - return { - uid: null, - role: [], - permission: [], - tokenExpired: 0, - }; - } - let userInfo; - try { - userInfo = JSON.parse(b64DecodeUnicode(tokenArr[1])); - } - catch (error) { - throw new Error('获取当前用户信息出错,详细错误信息为:' + error.message); - } - userInfo.tokenExpired = userInfo.exp * 1000; - delete userInfo.exp; - delete userInfo.iat; - return userInfo; - } - function uniIdMixin(globalProperties) { - globalProperties.uniIDHasRole = function (roleId) { - const { role } = getCurrentUserInfo(); - return role.indexOf(roleId) > -1; - }; - globalProperties.uniIDHasPermission = function (permissionId) { - const { permission } = getCurrentUserInfo(); - return this.uniIDHasRole('admin') || permission.indexOf(permissionId) > -1; - }; - globalProperties.uniIDTokenValid = function () { - const { tokenExpired } = getCurrentUserInfo(); - return tokenExpired > Date.now(); - }; - } - - function initApp(app) { - const appConfig = app._context.config; - if (isFunction(app._component.onError)) { - appConfig.errorHandler = errorHandler; - } - initOptionMergeStrategies(appConfig.optionMergeStrategies); - const globalProperties = appConfig.globalProperties; - { - uniIdMixin(globalProperties); - } - { - globalProperties.$set = set; - globalProperties.$applyOptions = applyOptions; - } - } - let isInitEntryPage = false; function initEntry() { if (isInitEntryPage) { @@ -17520,15 +17532,11 @@ var serviceContext = (function (vue) { function initAppLaunch(appVm) { const { entryPagePath, entryPageQuery, referrerInfo } = __uniConfig; - const args = extend({ - // 为了让 uni-stat 在 uni.onLaunch 中可以 mixin - app: { mixin: appVm.$.appContext.app.mixin }, - }, initLaunchOptions({ + const args = initLaunchOptions({ path: entryPagePath, query: entryPageQuery, referrerInfo: referrerInfo, - })); - injectAppLaunchHooks(appVm.$); + }); invokeHook(appVm, ON_LAUNCH, args); invokeHook(appVm, ON_SHOW, args); // https://tower.im/teams/226535/todos/16905/ @@ -19946,7 +19954,7 @@ var serviceContext = (function (vue) { $off: $off, $once: $once, $emit: $emit, - onAppLaunch: onAppLaunch, + onCreateVueApp: onCreateVueApp, onLocaleChange: onLocaleChange, setPageMeta: setPageMeta, getEnterOptionsSync: getEnterOptionsSync, diff --git a/packages/uni-app-plus/src/service/api/index.ts b/packages/uni-app-plus/src/service/api/index.ts index ab999f1e3..357df0f9b 100644 --- a/packages/uni-app-plus/src/service/api/index.ts +++ b/packages/uni-app-plus/src/service/api/index.ts @@ -110,7 +110,7 @@ export { $off, $once, $emit, - onAppLaunch, + onCreateVueApp, onLocaleChange, setPageMeta, getEnterOptionsSync, diff --git a/packages/uni-app-plus/src/service/framework/app/initAppLaunch.ts b/packages/uni-app-plus/src/service/framework/app/initAppLaunch.ts index de819b365..dd7c50011 100644 --- a/packages/uni-app-plus/src/service/framework/app/initAppLaunch.ts +++ b/packages/uni-app-plus/src/service/framework/app/initAppLaunch.ts @@ -1,5 +1,3 @@ -import { extend } from '@vue/shared' -import { injectAppLaunchHooks } from '@dcloudio/uni-api' import { invokeHook } from '@dcloudio/uni-core' import { ON_LAUNCH, ON_SHOW, ON_HIDE } from '@dcloudio/uni-shared' import { ComponentPublicInstance } from 'vue' @@ -7,18 +5,11 @@ import { initLaunchOptions } from './utils' export function initAppLaunch(appVm: ComponentPublicInstance) { const { entryPagePath, entryPageQuery, referrerInfo } = __uniConfig - const args = extend( - { - // 为了让 uni-stat 在 uni.onLaunch 中可以 mixin - app: { mixin: appVm.$.appContext.app.mixin }, - }, - initLaunchOptions({ - path: entryPagePath, - query: entryPageQuery, - referrerInfo: referrerInfo, - }) - ) - injectAppLaunchHooks(appVm.$) + const args = initLaunchOptions({ + path: entryPagePath, + query: entryPageQuery, + referrerInfo: referrerInfo, + }) invokeHook(appVm, ON_LAUNCH, args) invokeHook(appVm, ON_SHOW, args) // https://tower.im/teams/226535/todos/16905/ diff --git a/packages/uni-app-plus/src/service/framework/app/utils.ts b/packages/uni-app-plus/src/service/framework/app/utils.ts index 92af7ef31..906ea197b 100644 --- a/packages/uni-app-plus/src/service/framework/app/utils.ts +++ b/packages/uni-app-plus/src/service/framework/app/utils.ts @@ -11,15 +11,15 @@ export function backbuttonListener() { } as UniApp.NavigateBackOptions) } -const enterOptions: LaunchOptions = createLaunchOptions() -const launchOptions: LaunchOptions = createLaunchOptions() +const enterOptions: LaunchOptions = /*#__PURE__*/ createLaunchOptions() +const launchOptions: LaunchOptions = /*#__PURE__*/ createLaunchOptions() export function getLaunchOptions() { - return launchOptions + return extend({}, launchOptions) } export function getEnterOptions() { - return enterOptions + return extend({}, enterOptions) } export function initEnterOptions({ @@ -45,7 +45,7 @@ export function initLaunchOptions({ referrerInfo: referrerInfo || {}, }) extend(enterOptions, launchOptions) - return launchOptions + return extend({}, launchOptions) } export interface RedirectInfo extends Omit { diff --git a/packages/uni-h5-vite/lib/api.json b/packages/uni-h5-vite/lib/api.json index 54d489e06..db8402ad3 100644 --- a/packages/uni-h5-vite/lib/api.json +++ b/packages/uni-h5-vite/lib/api.json @@ -79,8 +79,8 @@ "offPushMessage", "offWindowResize", "onAccelerometerChange", - "onAppLaunch", "onCompassChange", + "onCreateVueApp", "onGyroscopeChange", "onLocaleChange", "onMemoryWarning", diff --git a/packages/uni-h5/dist/uni-h5.cjs.js b/packages/uni-h5/dist/uni-h5.cjs.js index 40eb998b5..6a6bb9ddd 100644 --- a/packages/uni-h5/dist/uni-h5.cjs.js +++ b/packages/uni-h5/dist/uni-h5.cjs.js @@ -1455,6 +1455,151 @@ const SetNavigationBarTitleProtocol = { }; const API_SHOW_NAVIGATION_BAR_LOADING = "showNavigationBarLoading"; const API_HIDE_NAVIGATION_BAR_LOADING = "hideNavigationBarLoading"; +function injectLifecycleHook(name, hook, publicThis, instance) { + if (shared.isFunction(hook)) { + vue.injectHook(name, hook.bind(publicThis), instance); + } +} +function initHooks(options, instance, publicThis) { + const mpType = options.mpType || publicThis.$mpType; + Object.keys(options).forEach((name) => { + if (name.indexOf("on") === 0) { + const hooks = options[name]; + if (shared.isArray(hooks)) { + hooks.forEach((hook) => injectLifecycleHook(name, hook, publicThis, instance)); + } else { + injectLifecycleHook(name, hooks, publicThis, instance); + } + } + }); + if (mpType === "page") { + instance.__isVisible = true; + try { + invokeHook(publicThis, uniShared.ON_LOAD, instance.attrs.__pageQuery); + delete instance.attrs.__pageQuery; + } catch (e2) { + console.error(e2.message + uniShared.LINEFEED + e2.stack); + } + vue.nextTick(() => { + invokeHook(publicThis, uniShared.ON_SHOW); + }); + } +} +function applyOptions(options, instance, publicThis) { + initHooks(options, instance, publicThis); +} +function set(target, key, val) { + return target[key] = val; +} +function errorHandler(err, instance, info) { + if (!instance) { + throw err; + } + const app = getApp(); + if (!app || !app.$vm) { + throw err; + } + { + invokeHook(app.$vm, uniShared.ON_ERROR, err); + } +} +function mergeAsArray(to, from) { + return to ? [...new Set([].concat(to, from))] : from; +} +function initOptionMergeStrategies(optionMergeStrategies) { + uniShared.UniLifecycleHooks.forEach((name) => { + optionMergeStrategies[name] = mergeAsArray; + }); +} +let realAtob; +const b64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="; +const b64re = /^(?:[A-Za-z\d+/]{4})*?(?:[A-Za-z\d+/]{2}(?:==)?|[A-Za-z\d+/]{3}=?)?$/; +if (typeof atob !== "function") { + realAtob = function(str) { + str = String(str).replace(/[\t\n\f\r ]+/g, ""); + if (!b64re.test(str)) { + throw new Error("Failed to execute 'atob' on 'Window': The string to be decoded is not correctly encoded."); + } + str += "==".slice(2 - (str.length & 3)); + var bitmap; + var result = ""; + var r1; + var r2; + var i = 0; + for (; i < str.length; ) { + bitmap = b64.indexOf(str.charAt(i++)) << 18 | b64.indexOf(str.charAt(i++)) << 12 | (r1 = b64.indexOf(str.charAt(i++))) << 6 | (r2 = b64.indexOf(str.charAt(i++))); + result += r1 === 64 ? String.fromCharCode(bitmap >> 16 & 255) : r2 === 64 ? String.fromCharCode(bitmap >> 16 & 255, bitmap >> 8 & 255) : String.fromCharCode(bitmap >> 16 & 255, bitmap >> 8 & 255, bitmap & 255); + } + return result; + }; +} else { + realAtob = atob; +} +function b64DecodeUnicode(str) { + return decodeURIComponent(realAtob(str).split("").map(function(c) { + return "%" + ("00" + c.charCodeAt(0).toString(16)).slice(-2); + }).join("")); +} +function getCurrentUserInfo() { + const token = uni.getStorageSync("uni_id_token") || ""; + const tokenArr = token.split("."); + if (!token || tokenArr.length !== 3) { + return { + uid: null, + role: [], + permission: [], + tokenExpired: 0 + }; + } + let userInfo; + try { + userInfo = JSON.parse(b64DecodeUnicode(tokenArr[1])); + } catch (error) { + throw new Error("\u83B7\u53D6\u5F53\u524D\u7528\u6237\u4FE1\u606F\u51FA\u9519\uFF0C\u8BE6\u7EC6\u9519\u8BEF\u4FE1\u606F\u4E3A\uFF1A" + error.message); + } + userInfo.tokenExpired = userInfo.exp * 1e3; + delete userInfo.exp; + delete userInfo.iat; + return userInfo; +} +function uniIdMixin(globalProperties) { + globalProperties.uniIDHasRole = function(roleId) { + const { role } = getCurrentUserInfo(); + return role.indexOf(roleId) > -1; + }; + globalProperties.uniIDHasPermission = function(permissionId) { + const { permission } = getCurrentUserInfo(); + return this.uniIDHasRole("admin") || permission.indexOf(permissionId) > -1; + }; + globalProperties.uniIDTokenValid = function() { + const { tokenExpired } = getCurrentUserInfo(); + return tokenExpired > Date.now(); + }; +} +const createVueAppHooks = []; +function invokeCreateVueAppHook(app) { + createVueAppHooks.forEach((hook) => hook(app)); +} +function initApp$1(app) { + const appConfig = app._context.config; + if (shared.isFunction(app._component.onError)) { + appConfig.errorHandler = errorHandler; + } + initOptionMergeStrategies(appConfig.optionMergeStrategies); + const globalProperties = appConfig.globalProperties; + { + if (__UNI_FEATURE_UNI_CLOUD__) { + uniIdMixin(globalProperties); + } + } + { + globalProperties.$set = set; + globalProperties.$applyOptions = applyOptions; + } + { + invokeCreateVueAppHook(app); + } +} function saveImage(base64, dirname, callback) { callback(null, base64); } @@ -6542,144 +6687,6 @@ function useContextInfo(_id) { const id = _id || vm.id || `context${index$g++}`; return `${type}.${id}`; } -function injectLifecycleHook(name, hook, publicThis, instance) { - if (shared.isFunction(hook)) { - vue.injectHook(name, hook.bind(publicThis), instance); - } -} -function initHooks(options, instance, publicThis) { - const mpType = options.mpType || publicThis.$mpType; - Object.keys(options).forEach((name) => { - if (name.indexOf("on") === 0) { - const hooks = options[name]; - if (shared.isArray(hooks)) { - hooks.forEach((hook) => injectLifecycleHook(name, hook, publicThis, instance)); - } else { - injectLifecycleHook(name, hooks, publicThis, instance); - } - } - }); - if (mpType === "page") { - instance.__isVisible = true; - try { - invokeHook(publicThis, uniShared.ON_LOAD, instance.attrs.__pageQuery); - delete instance.attrs.__pageQuery; - } catch (e2) { - console.error(e2.message + uniShared.LINEFEED + e2.stack); - } - vue.nextTick(() => { - invokeHook(publicThis, uniShared.ON_SHOW); - }); - } -} -function applyOptions(options, instance, publicThis) { - initHooks(options, instance, publicThis); -} -function set(target, key, val) { - return target[key] = val; -} -function errorHandler(err, instance, info) { - if (!instance) { - throw err; - } - const app = getApp(); - if (!app || !app.$vm) { - throw err; - } - { - invokeHook(app.$vm, uniShared.ON_ERROR, err); - } -} -function mergeAsArray(to, from) { - return to ? [...new Set([].concat(to, from))] : from; -} -function initOptionMergeStrategies(optionMergeStrategies) { - uniShared.UniLifecycleHooks.forEach((name) => { - optionMergeStrategies[name] = mergeAsArray; - }); -} -let realAtob; -const b64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="; -const b64re = /^(?:[A-Za-z\d+/]{4})*?(?:[A-Za-z\d+/]{2}(?:==)?|[A-Za-z\d+/]{3}=?)?$/; -if (typeof atob !== "function") { - realAtob = function(str) { - str = String(str).replace(/[\t\n\f\r ]+/g, ""); - if (!b64re.test(str)) { - throw new Error("Failed to execute 'atob' on 'Window': The string to be decoded is not correctly encoded."); - } - str += "==".slice(2 - (str.length & 3)); - var bitmap; - var result = ""; - var r1; - var r2; - var i = 0; - for (; i < str.length; ) { - bitmap = b64.indexOf(str.charAt(i++)) << 18 | b64.indexOf(str.charAt(i++)) << 12 | (r1 = b64.indexOf(str.charAt(i++))) << 6 | (r2 = b64.indexOf(str.charAt(i++))); - result += r1 === 64 ? String.fromCharCode(bitmap >> 16 & 255) : r2 === 64 ? String.fromCharCode(bitmap >> 16 & 255, bitmap >> 8 & 255) : String.fromCharCode(bitmap >> 16 & 255, bitmap >> 8 & 255, bitmap & 255); - } - return result; - }; -} else { - realAtob = atob; -} -function b64DecodeUnicode(str) { - return decodeURIComponent(realAtob(str).split("").map(function(c) { - return "%" + ("00" + c.charCodeAt(0).toString(16)).slice(-2); - }).join("")); -} -function getCurrentUserInfo() { - const token = uni.getStorageSync("uni_id_token") || ""; - const tokenArr = token.split("."); - if (!token || tokenArr.length !== 3) { - return { - uid: null, - role: [], - permission: [], - tokenExpired: 0 - }; - } - let userInfo; - try { - userInfo = JSON.parse(b64DecodeUnicode(tokenArr[1])); - } catch (error) { - throw new Error("\u83B7\u53D6\u5F53\u524D\u7528\u6237\u4FE1\u606F\u51FA\u9519\uFF0C\u8BE6\u7EC6\u9519\u8BEF\u4FE1\u606F\u4E3A\uFF1A" + error.message); - } - userInfo.tokenExpired = userInfo.exp * 1e3; - delete userInfo.exp; - delete userInfo.iat; - return userInfo; -} -function uniIdMixin(globalProperties) { - globalProperties.uniIDHasRole = function(roleId) { - const { role } = getCurrentUserInfo(); - return role.indexOf(roleId) > -1; - }; - globalProperties.uniIDHasPermission = function(permissionId) { - const { permission } = getCurrentUserInfo(); - return this.uniIDHasRole("admin") || permission.indexOf(permissionId) > -1; - }; - globalProperties.uniIDTokenValid = function() { - const { tokenExpired } = getCurrentUserInfo(); - return tokenExpired > Date.now(); - }; -} -function initApp$1(app) { - const appConfig = app._context.config; - if (shared.isFunction(app._component.onError)) { - appConfig.errorHandler = errorHandler; - } - initOptionMergeStrategies(appConfig.optionMergeStrategies); - const globalProperties = appConfig.globalProperties; - { - if (__UNI_FEATURE_UNI_CLOUD__) { - uniIdMixin(globalProperties); - } - } - { - globalProperties.$set = set; - globalProperties.$applyOptions = applyOptions; - } -} const pageMetaKey = PolySymbol(process.env.NODE_ENV !== "production" ? "UniPageMeta" : "upm"); function usePageMeta() { return vue.inject(pageMetaKey); diff --git a/packages/uni-h5/dist/uni-h5.es.js b/packages/uni-h5/dist/uni-h5.es.js index 70890e1c1..dbf9bf9f7 100644 --- a/packages/uni-h5/dist/uni-h5.es.js +++ b/packages/uni-h5/dist/uni-h5.es.js @@ -1,6 +1,6 @@ -import { withModifiers, createVNode, getCurrentInstance, ref, defineComponent, openBlock, createElementBlock, provide, computed, watch, onUnmounted, inject, onBeforeUnmount, mergeProps, injectHook, reactive, onActivated, onMounted, nextTick, onBeforeMount, withDirectives, vShow, shallowRef, watchEffect, isVNode, Fragment, markRaw, Comment, createTextVNode, onBeforeActivate, onBeforeDeactivate, createBlock, renderList, onDeactivated, createApp, Transition, effectScope, withCtx, KeepAlive, resolveDynamicComponent, createElementVNode, normalizeStyle, renderSlot } from "vue"; +import { withModifiers, createVNode, getCurrentInstance, ref, defineComponent, openBlock, createElementBlock, provide, computed, watch, onUnmounted, inject, onBeforeUnmount, mergeProps, nextTick, injectHook, reactive, onActivated, onMounted, onBeforeMount, withDirectives, vShow, shallowRef, watchEffect, isVNode, Fragment, markRaw, Comment, createTextVNode, onBeforeActivate, onBeforeDeactivate, createBlock, renderList, onDeactivated, createApp, Transition, effectScope, withCtx, KeepAlive, resolveDynamicComponent, createElementVNode, normalizeStyle, renderSlot } from "vue"; import { isString, extend, stringifyStyle, parseStringStyle, isPlainObject, isFunction, capitalize, camelize, isArray, hasOwn, isObject, toRawType, makeMap as makeMap$1, isPromise, hyphenate, invokeArrayFns as invokeArrayFns$1 } from "@vue/shared"; -import { once, UNI_STORAGE_LOCALE, I18N_JSON_DELIMITERS, Emitter, passive, initCustomDatasetOnce, resolveComponentInstance, addLeadingSlash, invokeArrayFns, resolveOwnerVm, resolveOwnerEl, ON_WXS_INVOKE_CALL_METHOD, normalizeTarget, ON_RESIZE, ON_APP_ENTER_FOREGROUND, ON_APP_ENTER_BACKGROUND, ON_SHOW, ON_HIDE, ON_PAGE_SCROLL, ON_REACH_BOTTOM, EventChannel, SCHEME_RE, DATA_RE, getCustomDataset, LINEFEED, ON_ERROR, callOptions, ON_LAUNCH, PRIMARY_COLOR, removeLeadingSlash, getLen, debounce, ON_LOAD, UniLifecycleHooks, NAVBAR_HEIGHT, parseQuery, ON_UNLOAD, ON_REACH_BOTTOM_DISTANCE, decodedQuery, WEB_INVOKE_APPSERVICE, ON_WEB_INVOKE_APP_SERVICE, updateElementStyle, ON_BACK_PRESS, parseUrl, addFont, scrollTo, RESPONSIVE_MIN_WIDTH, formatDateTime, ON_NAVIGATION_BAR_BUTTON_TAP, ON_NAVIGATION_BAR_SEARCH_INPUT_CLICKED, ON_NAVIGATION_BAR_SEARCH_INPUT_FOCUS_CHANGED, ON_NAVIGATION_BAR_SEARCH_INPUT_CHANGED, ON_NAVIGATION_BAR_SEARCH_INPUT_CONFIRMED, ON_PULL_DOWN_REFRESH } from "@dcloudio/uni-shared"; +import { once, UNI_STORAGE_LOCALE, I18N_JSON_DELIMITERS, Emitter, passive, initCustomDatasetOnce, resolveComponentInstance, addLeadingSlash, invokeArrayFns, resolveOwnerVm, resolveOwnerEl, ON_WXS_INVOKE_CALL_METHOD, normalizeTarget, ON_RESIZE, ON_APP_ENTER_FOREGROUND, ON_APP_ENTER_BACKGROUND, ON_SHOW, ON_HIDE, ON_PAGE_SCROLL, ON_REACH_BOTTOM, EventChannel, SCHEME_RE, DATA_RE, getCustomDataset, LINEFEED, ON_ERROR, callOptions, PRIMARY_COLOR, removeLeadingSlash, getLen, ON_LOAD, UniLifecycleHooks, debounce, NAVBAR_HEIGHT, parseQuery, ON_UNLOAD, ON_REACH_BOTTOM_DISTANCE, decodedQuery, WEB_INVOKE_APPSERVICE, ON_WEB_INVOKE_APP_SERVICE, updateElementStyle, ON_BACK_PRESS, parseUrl, addFont, scrollTo, RESPONSIVE_MIN_WIDTH, formatDateTime, ON_NAVIGATION_BAR_BUTTON_TAP, ON_NAVIGATION_BAR_SEARCH_INPUT_CLICKED, ON_NAVIGATION_BAR_SEARCH_INPUT_FOCUS_CHANGED, ON_NAVIGATION_BAR_SEARCH_INPUT_CHANGED, ON_NAVIGATION_BAR_SEARCH_INPUT_CONFIRMED, ON_PULL_DOWN_REFRESH } from "@dcloudio/uni-shared"; import { initVueI18n, isI18nStr, LOCALE_EN, LOCALE_ES, LOCALE_FR, LOCALE_ZH_HANS, LOCALE_ZH_HANT } from "@dcloudio/uni-i18n"; import { useRoute, createRouter, createWebHistory, createWebHashHistory, useRouter, isNavigationFailure, RouterView } from "vue-router"; const isEnableLocale = /* @__PURE__ */ once(() => typeof __uniConfig !== "undefined" && __uniConfig.locales && !!Object.keys(__uniConfig.locales).length); @@ -4472,19 +4472,6 @@ const getSelectedTextRange$1 = /* @__PURE__ */ defineAsyncApi(API_GET_SELECTED_T } }); }); -const appLaunchHooks = []; -function onAppLaunch(hook) { - const app = getApp({ allowDefault: true }); - if (app && app.$vm) { - return injectHook(ON_LAUNCH, hook, app.$vm.$); - } - appLaunchHooks.push(hook); -} -function injectAppLaunchHooks(appInstance) { - appLaunchHooks.forEach((hook) => { - injectHook(ON_LAUNCH, hook, appInstance); - }); -} const API_GET_ENTER_OPTIONS_SYNC = "getEnterOptionsSync"; const getEnterOptionsSync = /* @__PURE__ */ defineSyncApi(API_GET_ENTER_OPTIONS_SYNC, () => { return getEnterOptions(); @@ -5430,6 +5417,159 @@ const SetTabBarBadgeOptions = { } }, IndexOptions.formatArgs) }; +function injectLifecycleHook(name, hook, publicThis, instance2) { + if (isFunction(hook)) { + injectHook(name, hook.bind(publicThis), instance2); + } +} +function initHooks(options, instance2, publicThis) { + const mpType = options.mpType || publicThis.$mpType; + Object.keys(options).forEach((name) => { + if (name.indexOf("on") === 0) { + const hooks = options[name]; + if (isArray(hooks)) { + hooks.forEach((hook) => injectLifecycleHook(name, hook, publicThis, instance2)); + } else { + injectLifecycleHook(name, hooks, publicThis, instance2); + } + } + }); + if (mpType === "page") { + instance2.__isVisible = true; + try { + invokeHook(publicThis, ON_LOAD, instance2.attrs.__pageQuery); + delete instance2.attrs.__pageQuery; + } catch (e2) { + console.error(e2.message + LINEFEED + e2.stack); + } + nextTick(() => { + invokeHook(publicThis, ON_SHOW); + }); + } +} +function applyOptions(options, instance2, publicThis) { + initHooks(options, instance2, publicThis); +} +function set(target, key, val) { + return target[key] = val; +} +function errorHandler(err, instance2, info) { + if (!instance2) { + throw err; + } + const app = getApp(); + if (!app || !app.$vm) { + throw err; + } + { + invokeHook(app.$vm, ON_ERROR, err); + } +} +function mergeAsArray(to, from) { + return to ? [...new Set([].concat(to, from))] : from; +} +function initOptionMergeStrategies(optionMergeStrategies) { + UniLifecycleHooks.forEach((name) => { + optionMergeStrategies[name] = mergeAsArray; + }); +} +let realAtob; +const b64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="; +const b64re = /^(?:[A-Za-z\d+/]{4})*?(?:[A-Za-z\d+/]{2}(?:==)?|[A-Za-z\d+/]{3}=?)?$/; +if (typeof atob !== "function") { + realAtob = function(str) { + str = String(str).replace(/[\t\n\f\r ]+/g, ""); + if (!b64re.test(str)) { + throw new Error("Failed to execute 'atob' on 'Window': The string to be decoded is not correctly encoded."); + } + str += "==".slice(2 - (str.length & 3)); + var bitmap; + var result = ""; + var r1; + var r2; + var i = 0; + for (; i < str.length; ) { + bitmap = b64.indexOf(str.charAt(i++)) << 18 | b64.indexOf(str.charAt(i++)) << 12 | (r1 = b64.indexOf(str.charAt(i++))) << 6 | (r2 = b64.indexOf(str.charAt(i++))); + result += r1 === 64 ? String.fromCharCode(bitmap >> 16 & 255) : r2 === 64 ? String.fromCharCode(bitmap >> 16 & 255, bitmap >> 8 & 255) : String.fromCharCode(bitmap >> 16 & 255, bitmap >> 8 & 255, bitmap & 255); + } + return result; + }; +} else { + realAtob = atob; +} +function b64DecodeUnicode(str) { + return decodeURIComponent(realAtob(str).split("").map(function(c) { + return "%" + ("00" + c.charCodeAt(0).toString(16)).slice(-2); + }).join("")); +} +function getCurrentUserInfo() { + const token = uni.getStorageSync("uni_id_token") || ""; + const tokenArr = token.split("."); + if (!token || tokenArr.length !== 3) { + return { + uid: null, + role: [], + permission: [], + tokenExpired: 0 + }; + } + let userInfo; + try { + userInfo = JSON.parse(b64DecodeUnicode(tokenArr[1])); + } catch (error) { + throw new Error("\u83B7\u53D6\u5F53\u524D\u7528\u6237\u4FE1\u606F\u51FA\u9519\uFF0C\u8BE6\u7EC6\u9519\u8BEF\u4FE1\u606F\u4E3A\uFF1A" + error.message); + } + userInfo.tokenExpired = userInfo.exp * 1e3; + delete userInfo.exp; + delete userInfo.iat; + return userInfo; +} +function uniIdMixin(globalProperties) { + globalProperties.uniIDHasRole = function(roleId) { + const { role } = getCurrentUserInfo(); + return role.indexOf(roleId) > -1; + }; + globalProperties.uniIDHasPermission = function(permissionId) { + const { permission } = getCurrentUserInfo(); + return this.uniIDHasRole("admin") || permission.indexOf(permissionId) > -1; + }; + globalProperties.uniIDTokenValid = function() { + const { tokenExpired } = getCurrentUserInfo(); + return tokenExpired > Date.now(); + }; +} +let vueApp; +const createVueAppHooks = []; +function onCreateVueApp(hook) { + if (vueApp) { + return hook(vueApp); + } + createVueAppHooks.push(hook); +} +function invokeCreateVueAppHook(app) { + vueApp = app; + createVueAppHooks.forEach((hook) => hook(app)); +} +function initApp$1(app) { + const appConfig = app._context.config; + if (isFunction(app._component.onError)) { + appConfig.errorHandler = errorHandler; + } + initOptionMergeStrategies(appConfig.optionMergeStrategies); + const globalProperties = appConfig.globalProperties; + { + if (__UNI_FEATURE_UNI_CLOUD__) { + uniIdMixin(globalProperties); + } + } + { + globalProperties.$set = set; + globalProperties.$applyOptions = applyOptions; + } + { + invokeCreateVueAppHook(app); + } +} const initIntersectionObserverPolyfill = function() { if (typeof window !== "object") { return; @@ -6159,13 +6299,13 @@ function revokeObjectURL(url) { URL.revokeObjectURL(url); delete files[url]; } -const launchOptions = createLaunchOptions(); -const enterOptions = createLaunchOptions(); +const launchOptions = /* @__PURE__ */ createLaunchOptions(); +const enterOptions = /* @__PURE__ */ createLaunchOptions(); function getEnterOptions() { - return enterOptions; + return extend({}, enterOptions); } function getLaunchOptions() { - return launchOptions; + return extend({}, launchOptions); } function initLaunchOptions({ path, @@ -6176,7 +6316,7 @@ function initLaunchOptions({ query }); extend(enterOptions, launchOptions); - return launchOptions; + return extend({}, launchOptions); } const inflateRaw = (...args) => { }; @@ -13509,144 +13649,6 @@ function useContextInfo(_id) { function getContextInfo(el) { return el.__uniContextInfo; } -function injectLifecycleHook(name, hook, publicThis, instance2) { - if (isFunction(hook)) { - injectHook(name, hook.bind(publicThis), instance2); - } -} -function initHooks(options, instance2, publicThis) { - const mpType = options.mpType || publicThis.$mpType; - Object.keys(options).forEach((name) => { - if (name.indexOf("on") === 0) { - const hooks = options[name]; - if (isArray(hooks)) { - hooks.forEach((hook) => injectLifecycleHook(name, hook, publicThis, instance2)); - } else { - injectLifecycleHook(name, hooks, publicThis, instance2); - } - } - }); - if (mpType === "page") { - instance2.__isVisible = true; - try { - invokeHook(publicThis, ON_LOAD, instance2.attrs.__pageQuery); - delete instance2.attrs.__pageQuery; - } catch (e2) { - console.error(e2.message + LINEFEED + e2.stack); - } - nextTick(() => { - invokeHook(publicThis, ON_SHOW); - }); - } -} -function applyOptions(options, instance2, publicThis) { - initHooks(options, instance2, publicThis); -} -function set(target, key, val) { - return target[key] = val; -} -function errorHandler(err, instance2, info) { - if (!instance2) { - throw err; - } - const app = getApp(); - if (!app || !app.$vm) { - throw err; - } - { - invokeHook(app.$vm, ON_ERROR, err); - } -} -function mergeAsArray(to, from) { - return to ? [...new Set([].concat(to, from))] : from; -} -function initOptionMergeStrategies(optionMergeStrategies) { - UniLifecycleHooks.forEach((name) => { - optionMergeStrategies[name] = mergeAsArray; - }); -} -let realAtob; -const b64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="; -const b64re = /^(?:[A-Za-z\d+/]{4})*?(?:[A-Za-z\d+/]{2}(?:==)?|[A-Za-z\d+/]{3}=?)?$/; -if (typeof atob !== "function") { - realAtob = function(str) { - str = String(str).replace(/[\t\n\f\r ]+/g, ""); - if (!b64re.test(str)) { - throw new Error("Failed to execute 'atob' on 'Window': The string to be decoded is not correctly encoded."); - } - str += "==".slice(2 - (str.length & 3)); - var bitmap; - var result = ""; - var r1; - var r2; - var i = 0; - for (; i < str.length; ) { - bitmap = b64.indexOf(str.charAt(i++)) << 18 | b64.indexOf(str.charAt(i++)) << 12 | (r1 = b64.indexOf(str.charAt(i++))) << 6 | (r2 = b64.indexOf(str.charAt(i++))); - result += r1 === 64 ? String.fromCharCode(bitmap >> 16 & 255) : r2 === 64 ? String.fromCharCode(bitmap >> 16 & 255, bitmap >> 8 & 255) : String.fromCharCode(bitmap >> 16 & 255, bitmap >> 8 & 255, bitmap & 255); - } - return result; - }; -} else { - realAtob = atob; -} -function b64DecodeUnicode(str) { - return decodeURIComponent(realAtob(str).split("").map(function(c) { - return "%" + ("00" + c.charCodeAt(0).toString(16)).slice(-2); - }).join("")); -} -function getCurrentUserInfo() { - const token = uni.getStorageSync("uni_id_token") || ""; - const tokenArr = token.split("."); - if (!token || tokenArr.length !== 3) { - return { - uid: null, - role: [], - permission: [], - tokenExpired: 0 - }; - } - let userInfo; - try { - userInfo = JSON.parse(b64DecodeUnicode(tokenArr[1])); - } catch (error) { - throw new Error("\u83B7\u53D6\u5F53\u524D\u7528\u6237\u4FE1\u606F\u51FA\u9519\uFF0C\u8BE6\u7EC6\u9519\u8BEF\u4FE1\u606F\u4E3A\uFF1A" + error.message); - } - userInfo.tokenExpired = userInfo.exp * 1e3; - delete userInfo.exp; - delete userInfo.iat; - return userInfo; -} -function uniIdMixin(globalProperties) { - globalProperties.uniIDHasRole = function(roleId) { - const { role } = getCurrentUserInfo(); - return role.indexOf(roleId) > -1; - }; - globalProperties.uniIDHasPermission = function(permissionId) { - const { permission } = getCurrentUserInfo(); - return this.uniIDHasRole("admin") || permission.indexOf(permissionId) > -1; - }; - globalProperties.uniIDTokenValid = function() { - const { tokenExpired } = getCurrentUserInfo(); - return tokenExpired > Date.now(); - }; -} -function initApp$1(app) { - const appConfig = app._context.config; - if (isFunction(app._component.onError)) { - appConfig.errorHandler = errorHandler; - } - initOptionMergeStrategies(appConfig.optionMergeStrategies); - const globalProperties = appConfig.globalProperties; - { - if (__UNI_FEATURE_UNI_CLOUD__) { - uniIdMixin(globalProperties); - } - } - { - globalProperties.$set = set; - globalProperties.$applyOptions = applyOptions; - } -} const pageMetaKey = PolySymbol(process.env.NODE_ENV !== "production" ? "UniPageMeta" : "upm"); function usePageMeta() { return inject(pageMetaKey); @@ -14140,13 +14142,11 @@ function setupApp(comp) { const route = usePageRoute(); const onLaunch = () => { const { onLaunch: onLaunch2, onShow, onPageNotFound } = instance2; - const path = route.path.substr(1); - const launchOptions2 = extend({ - app: { mixin: instance2.appContext.app.mixin } - }, initLaunchOptions({ + const path = route.path.slice(1); + const launchOptions2 = initLaunchOptions({ path: path || __uniRoutes[0].meta.route, query: decodedQuery(route.query) - })); + }); onLaunch2 && invokeArrayFns$1(onLaunch2, launchOptions2); onShow && invokeArrayFns$1(onShow, launchOptions2); if (__UNI_FEATURE_PAGES__) { @@ -14162,7 +14162,6 @@ function setupApp(comp) { } } }; - injectAppLaunchHooks(instance2); if (__UNI_FEATURE_PAGES__) { useRouter().isReady().then(onLaunch); } else { @@ -19846,7 +19845,7 @@ var api = { $off, $once, $emit, - onAppLaunch, + onCreateVueApp, onLocaleChange, setPageMeta, getEnterOptionsSync, @@ -22016,4 +22015,4 @@ var index = /* @__PURE__ */ defineSystemComponent({ return openBlock(), createBlock("div", clazz, [loadingVNode]); } }); -export { $emit, $off, $on, $once, index$8 as Ad, index$7 as AdContentPage, index$6 as AdDraw, index$1 as AsyncErrorComponent, index as AsyncLoadingComponent, index$y as Button, index$5 as Camera, index$w as Canvas, index$u as Checkbox, index$v as CheckboxGroup, index$a as CoverImage, index$b as CoverView, index$t as Editor, index$A as Form, index$s as Icon, index$r as Image, Input, index$z as Label, LayoutComponent, index$4 as LivePlayer, index$3 as LivePusher, Map$1 as Map, MovableArea, MovableView, index$q as Navigator, index$2 as PageComponent, index$9 as Picker, PickerView, PickerViewColumn, index$p as Progress, index$n as Radio, index$o as RadioGroup, ResizeSensor, index$m as RichText, ScrollView, index$l as Slider, Swiper, SwiperItem, index$k as Switch, index$j as Text, index$i as Textarea, UniServiceJSBridge$1 as UniServiceJSBridge, UniViewJSBridge$1 as UniViewJSBridge, index$e as Video, index$h as View, index$d as WebView, addInterceptor, addPhoneContact, arrayBufferToBase64, base64ToArrayBuffer, canIUse, canvasGetImageData, canvasPutImageData, canvasToTempFilePath, chooseFile, chooseImage, chooseLocation, chooseVideo, clearStorage, clearStorageSync, closePreviewImage, closeSocket, connectSocket, createAnimation$1 as createAnimation, createCameraContext, createCanvasContext, createInnerAudioContext, createIntersectionObserver, createLivePlayerContext, createMapContext, createMediaQueryObserver, createSelectorQuery, createVideoContext, cssBackdropFilter, cssConstant, cssEnv, cssVar, downloadFile, getApp$1 as getApp, getClipboardData, getCurrentPages$1 as getCurrentPages, getEnterOptionsSync, getFileInfo, getImageInfo, getLaunchOptionsSync, getLeftWindowStyle, getLocale, getLocation, getNetworkType, getProvider, getPushCid, getRealPath, getRecorderManager, getRightWindowStyle, getSavedFileInfo, getSavedFileList, getScreenBrightness, getSelectedTextRange$1 as getSelectedTextRange, getStorage, getStorageInfo, getStorageInfoSync, getStorageSync, getSystemInfo, getSystemInfoSync, getTopWindowStyle, getVideoInfo, hideKeyboard, hideLeftWindow, hideLoading, hideNavigationBarLoading, hideRightWindow, hideTabBar, hideTabBarRedDot, hideToast, hideTopWindow, interceptors, invokePushCallback, loadFontFace, login, makePhoneCall, navigateBack, navigateTo, offAccelerometerChange, offCompassChange, offNetworkStatusChange, offPushMessage, offWindowResize, onAccelerometerChange, onAppLaunch, onCompassChange, onGyroscopeChange, onLocaleChange, onMemoryWarning, onNetworkStatusChange, onPushMessage, onSocketClose, onSocketError, onSocketMessage, onSocketOpen, onTabBarMidButtonTap, onUserCaptureScreen, onWindowResize, openDocument, openLocation, pageScrollTo, index$f as plugin, preloadPage, previewImage, reLaunch, redirectTo, removeInterceptor, removeSavedFileInfo, removeStorage, removeStorageSync, removeTabBarBadge, request, saveFile, saveImageToPhotosAlbum, saveVideoToPhotosAlbum, scanCode, sendSocketMessage, setClipboardData, setKeepScreenOn, setLeftWindowStyle, setLocale, setNavigationBarColor, setNavigationBarTitle, setPageMeta, setRightWindowStyle, setScreenBrightness, setStorage, setStorageSync, setTabBarBadge, setTabBarItem, setTabBarStyle, setTopWindowStyle, setupApp, setupPage, setupWindow, showActionSheet, showLeftWindow, showLoading, showModal, showNavigationBarLoading, showRightWindow, showTabBar, showTabBarRedDot, showToast, showTopWindow, startAccelerometer, startCompass, startGyroscope, startPullDownRefresh, stopAccelerometer, stopCompass, stopGyroscope, stopPullDownRefresh, switchTab, uni$1 as uni, uploadFile, upx2px, useI18n, useTabBar, vibrateLong, vibrateShort }; +export { $emit, $off, $on, $once, index$8 as Ad, index$7 as AdContentPage, index$6 as AdDraw, index$1 as AsyncErrorComponent, index as AsyncLoadingComponent, index$y as Button, index$5 as Camera, index$w as Canvas, index$u as Checkbox, index$v as CheckboxGroup, index$a as CoverImage, index$b as CoverView, index$t as Editor, index$A as Form, index$s as Icon, index$r as Image, Input, index$z as Label, LayoutComponent, index$4 as LivePlayer, index$3 as LivePusher, Map$1 as Map, MovableArea, MovableView, index$q as Navigator, index$2 as PageComponent, index$9 as Picker, PickerView, PickerViewColumn, index$p as Progress, index$n as Radio, index$o as RadioGroup, ResizeSensor, index$m as RichText, ScrollView, index$l as Slider, Swiper, SwiperItem, index$k as Switch, index$j as Text, index$i as Textarea, UniServiceJSBridge$1 as UniServiceJSBridge, UniViewJSBridge$1 as UniViewJSBridge, index$e as Video, index$h as View, index$d as WebView, addInterceptor, addPhoneContact, arrayBufferToBase64, base64ToArrayBuffer, canIUse, canvasGetImageData, canvasPutImageData, canvasToTempFilePath, chooseFile, chooseImage, chooseLocation, chooseVideo, clearStorage, clearStorageSync, closePreviewImage, closeSocket, connectSocket, createAnimation$1 as createAnimation, createCameraContext, createCanvasContext, createInnerAudioContext, createIntersectionObserver, createLivePlayerContext, createMapContext, createMediaQueryObserver, createSelectorQuery, createVideoContext, cssBackdropFilter, cssConstant, cssEnv, cssVar, downloadFile, getApp$1 as getApp, getClipboardData, getCurrentPages$1 as getCurrentPages, getEnterOptionsSync, getFileInfo, getImageInfo, getLaunchOptionsSync, getLeftWindowStyle, getLocale, getLocation, getNetworkType, getProvider, getPushCid, getRealPath, getRecorderManager, getRightWindowStyle, getSavedFileInfo, getSavedFileList, getScreenBrightness, getSelectedTextRange$1 as getSelectedTextRange, getStorage, getStorageInfo, getStorageInfoSync, getStorageSync, getSystemInfo, getSystemInfoSync, getTopWindowStyle, getVideoInfo, hideKeyboard, hideLeftWindow, hideLoading, hideNavigationBarLoading, hideRightWindow, hideTabBar, hideTabBarRedDot, hideToast, hideTopWindow, interceptors, invokePushCallback, loadFontFace, login, makePhoneCall, navigateBack, navigateTo, offAccelerometerChange, offCompassChange, offNetworkStatusChange, offPushMessage, offWindowResize, onAccelerometerChange, onCompassChange, onCreateVueApp, onGyroscopeChange, onLocaleChange, onMemoryWarning, onNetworkStatusChange, onPushMessage, onSocketClose, onSocketError, onSocketMessage, onSocketOpen, onTabBarMidButtonTap, onUserCaptureScreen, onWindowResize, openDocument, openLocation, pageScrollTo, index$f as plugin, preloadPage, previewImage, reLaunch, redirectTo, removeInterceptor, removeSavedFileInfo, removeStorage, removeStorageSync, removeTabBarBadge, request, saveFile, saveImageToPhotosAlbum, saveVideoToPhotosAlbum, scanCode, sendSocketMessage, setClipboardData, setKeepScreenOn, setLeftWindowStyle, setLocale, setNavigationBarColor, setNavigationBarTitle, setPageMeta, setRightWindowStyle, setScreenBrightness, setStorage, setStorageSync, setTabBarBadge, setTabBarItem, setTabBarStyle, setTopWindowStyle, setupApp, setupPage, setupWindow, showActionSheet, showLeftWindow, showLoading, showModal, showNavigationBarLoading, showRightWindow, showTabBar, showTabBarRedDot, showToast, showTopWindow, startAccelerometer, startCompass, startGyroscope, startPullDownRefresh, stopAccelerometer, stopCompass, stopGyroscope, stopPullDownRefresh, switchTab, uni$1 as uni, uploadFile, upx2px, useI18n, useTabBar, vibrateLong, vibrateShort }; diff --git a/packages/uni-h5/src/framework/setup/index.ts b/packages/uni-h5/src/framework/setup/index.ts index cbf55b1de..0079b5137 100644 --- a/packages/uni-h5/src/framework/setup/index.ts +++ b/packages/uni-h5/src/framework/setup/index.ts @@ -22,7 +22,6 @@ import { ON_WEB_INVOKE_APP_SERVICE, WEB_INVOKE_APPSERVICE, } from '@dcloudio/uni-shared' -import { injectAppLaunchHooks } from '@dcloudio/uni-api' import { subscribeViewMethod, unsubscribeViewMethod } from '@dcloudio/uni-core' import { LayoutComponent } from '../..' import { initApp } from './app' @@ -141,16 +140,11 @@ export function setupApp(comp: any) { } const onLaunch = () => { const { onLaunch, onShow, onPageNotFound } = instance - const path = route.path.substr(1) - const launchOptions = extend( - { - app: { mixin: instance.appContext.app.mixin }, - }, - initLaunchOptions({ - path: path || __uniRoutes[0].meta.route, - query: decodedQuery(route.query), - }) - ) + const path = route.path.slice(1) + const launchOptions = initLaunchOptions({ + path: path || __uniRoutes[0].meta.route, + query: decodedQuery(route.query), + }) onLaunch && invokeArrayFns(onLaunch, launchOptions) onShow && invokeArrayFns(onShow, launchOptions) if (__UNI_FEATURE_PAGES__) { @@ -167,7 +161,6 @@ export function setupApp(comp: any) { } } } - injectAppLaunchHooks(instance) if (__UNI_FEATURE_PAGES__) { // 等待ready后,再onLaunch,可以顺利获取到正确的path和query useRouter().isReady().then(onLaunch) diff --git a/packages/uni-h5/src/framework/setup/utils.ts b/packages/uni-h5/src/framework/setup/utils.ts index dc003b017..17fe27b64 100644 --- a/packages/uni-h5/src/framework/setup/utils.ts +++ b/packages/uni-h5/src/framework/setup/utils.ts @@ -1,16 +1,16 @@ import { extend } from '@vue/shared' import { createLaunchOptions, LaunchOptions } from '@dcloudio/uni-core' -const launchOptions: LaunchOptions = createLaunchOptions() +const launchOptions: LaunchOptions = /*#__PURE__*/ createLaunchOptions() -const enterOptions: LaunchOptions = createLaunchOptions() +const enterOptions: LaunchOptions = /*#__PURE__*/ createLaunchOptions() export function getEnterOptions() { - return enterOptions + return extend({}, enterOptions) } export function getLaunchOptions() { - return launchOptions + return extend({}, launchOptions) } export function initLaunchOptions({ @@ -25,5 +25,5 @@ export function initLaunchOptions({ query, }) extend(enterOptions, launchOptions) - return launchOptions + return extend({}, launchOptions) } diff --git a/packages/uni-h5/src/service/api/index.ts b/packages/uni-h5/src/service/api/index.ts index 0ba0e45d5..a37a5d801 100644 --- a/packages/uni-h5/src/service/api/index.ts +++ b/packages/uni-h5/src/service/api/index.ts @@ -92,7 +92,7 @@ export { $off, $once, $emit, - onAppLaunch, + onCreateVueApp, onLocaleChange, setPageMeta, getEnterOptionsSync, diff --git a/packages/uni-mp-alipay/dist/uni.api.esm.js b/packages/uni-mp-alipay/dist/uni.api.esm.js index ad2cf7f06..9097489cb 100644 --- a/packages/uni-mp-alipay/dist/uni.api.esm.js +++ b/packages/uni-mp-alipay/dist/uni.api.esm.js @@ -1,8 +1,4 @@ import { isArray, hasOwn, isString, isPlainObject, isObject, capitalize, toRawType, makeMap, isFunction, isPromise, extend } from '@vue/shared'; -import { injectHook } from 'vue'; - -//App -const ON_LAUNCH = 'onLaunch'; const eventChannels = {}; const eventChannelStack = []; @@ -40,15 +36,6 @@ const navigateTo = { }, }; -my.appLaunchHooks = []; -function onAppLaunch(hook) { - const app = getApp({ allowDefault: true }); - if (app && app.$vm) { - return injectHook(ON_LAUNCH, hook, app.$vm.$); - } - my.appLaunchHooks.push(hook); -} - function getBaseSystemInfo() { return my.getSystemInfoSync() } @@ -674,6 +661,24 @@ const offPushMessage = (fn) => { } }; +let vueApp; +const createVueAppHooks = []; +/** + * 提供 createApp 的回调事件,方便三方插件接收 App 对象,处理挂靠全局 mixin 之类的逻辑 + * @param hook + */ +function onCreateVueApp(hook) { + // TODO 每个 nvue 页面都会触发 + if (vueApp) { + return hook(vueApp); + } + createVueAppHooks.push(hook); +} +function invokeCreateVueAppHook(app) { + vueApp = app; + createVueAppHooks.forEach((hook) => hook(app)); +} + const SYNC_API_RE = /^\$|getLocale|setLocale|sendNativeEvent|restoreGlobal|getCurrentSubNVue|getMenuButtonBoundingClientRect|^report|interceptors|Interceptor$|getSubNVueById|requireNativePlugin|upx2px|hideKeyboard|canIUse|^create|Sync$|Manager$|base64ToArrayBuffer|arrayBufferToBase64/; const CONTEXT_API_RE = /^create|Manager$/; // Context例外情况 @@ -858,7 +863,8 @@ const baseApis = { interceptors, addInterceptor, removeInterceptor, - onAppLaunch, + onCreateVueApp, + invokeCreateVueAppHook, getLocale, setLocale, onLocaleChange, diff --git a/packages/uni-mp-alipay/dist/uni.mp.esm.js b/packages/uni-mp-alipay/dist/uni.mp.esm.js index 3e86106b0..d4cf792a9 100644 --- a/packages/uni-mp-alipay/dist/uni.mp.esm.js +++ b/packages/uni-mp-alipay/dist/uni.mp.esm.js @@ -1,5 +1,5 @@ import { camelize, isPlainObject, hasOwn, isArray, capitalize, isFunction, extend, isString } from '@vue/shared'; -import { injectHook, ref, findComponentPropsData, toRaw, updateProps, invalidateJob, getExposeProxy, EMPTY_OBJ, isRef, setTemplateRef, pruneComponentPropsCache } from 'vue'; +import { ref, findComponentPropsData, toRaw, updateProps, invalidateJob, getExposeProxy, EMPTY_OBJ, isRef, setTemplateRef, pruneComponentPropsCache } from 'vue'; // quickapp-webview 不能使用 default 作为插槽名称 const SLOT_DEFAULT_NAME = 'd'; @@ -307,13 +307,6 @@ function initRuntimeHooks(mpOptions, runtimeHooks) { }); } -my.appLaunchHooks = []; -function injectAppLaunchHooks(appInstance) { - my.appLaunchHooks.forEach((hook) => { - injectHook(ON_LAUNCH, hook, appInstance); - }); -} - const HOOKS = [ ON_SHOW, ON_HIDE, @@ -341,9 +334,8 @@ function parseApp(instance, parseAppOptions) { mpInstance: this, slots: [], }); - injectAppLaunchHooks(internalInstance); ctx.globalData = this.globalData; - instance.$callHook(ON_LAUNCH, extend({ app: { mixin: internalInstance.appContext.app.mixin } }, options)); + instance.$callHook(ON_LAUNCH, options); }, }; initLocale(instance); diff --git a/packages/uni-mp-baidu/dist/uni.api.esm.js b/packages/uni-mp-baidu/dist/uni.api.esm.js index e614fac8f..c978a158a 100644 --- a/packages/uni-mp-baidu/dist/uni.api.esm.js +++ b/packages/uni-mp-baidu/dist/uni.api.esm.js @@ -1,8 +1,4 @@ import { isArray, hasOwn, isString, isPlainObject, isObject, capitalize, toRawType, makeMap, isFunction, isPromise, extend } from '@vue/shared'; -import { injectHook } from 'vue'; - -//App -const ON_LAUNCH = 'onLaunch'; const eventChannels = {}; const eventChannelStack = []; @@ -40,15 +36,6 @@ const navigateTo = { }, }; -swan.appLaunchHooks = []; -function onAppLaunch(hook) { - const app = getApp({ allowDefault: true }); - if (app && app.$vm) { - return injectHook(ON_LAUNCH, hook, app.$vm.$); - } - swan.appLaunchHooks.push(hook); -} - function getBaseSystemInfo() { return swan.getSystemInfoSync() } @@ -674,6 +661,24 @@ const offPushMessage = (fn) => { } }; +let vueApp; +const createVueAppHooks = []; +/** + * 提供 createApp 的回调事件,方便三方插件接收 App 对象,处理挂靠全局 mixin 之类的逻辑 + * @param hook + */ +function onCreateVueApp(hook) { + // TODO 每个 nvue 页面都会触发 + if (vueApp) { + return hook(vueApp); + } + createVueAppHooks.push(hook); +} +function invokeCreateVueAppHook(app) { + vueApp = app; + createVueAppHooks.forEach((hook) => hook(app)); +} + const SYNC_API_RE = /^\$|getLocale|setLocale|sendNativeEvent|restoreGlobal|getCurrentSubNVue|getMenuButtonBoundingClientRect|^report|interceptors|Interceptor$|getSubNVueById|requireNativePlugin|upx2px|hideKeyboard|canIUse|^create|Sync$|Manager$|base64ToArrayBuffer|arrayBufferToBase64/; const CONTEXT_API_RE = /^create|Manager$/; // Context例外情况 @@ -858,7 +863,8 @@ const baseApis = { interceptors, addInterceptor, removeInterceptor, - onAppLaunch, + onCreateVueApp, + invokeCreateVueAppHook, getLocale, setLocale, onLocaleChange, diff --git a/packages/uni-mp-baidu/dist/uni.mp.esm.js b/packages/uni-mp-baidu/dist/uni.mp.esm.js index a0d171b67..75bf21881 100644 --- a/packages/uni-mp-baidu/dist/uni.mp.esm.js +++ b/packages/uni-mp-baidu/dist/uni.mp.esm.js @@ -1,5 +1,5 @@ import { isPlainObject, camelize, isArray, hasOwn, isFunction, extend } from '@vue/shared'; -import { injectHook, ref, nextTick, findComponentPropsData, toRaw, updateProps, invalidateJob, getExposeProxy, pruneComponentPropsCache } from 'vue'; +import { ref, nextTick, findComponentPropsData, toRaw, updateProps, invalidateJob, getExposeProxy, pruneComponentPropsCache } from 'vue'; // lifecycle // App and Page @@ -390,13 +390,6 @@ function initRuntimeHooks(mpOptions, runtimeHooks) { }); } -swan.appLaunchHooks = []; -function injectAppLaunchHooks(appInstance) { - swan.appLaunchHooks.forEach((hook) => { - injectHook(ON_LAUNCH, hook, appInstance); - }); -} - const HOOKS = [ ON_SHOW, ON_HIDE, @@ -421,9 +414,8 @@ function parseApp(instance, parseAppOptions) { mpInstance: this, slots: [], }); - injectAppLaunchHooks(internalInstance); ctx.globalData = this.globalData; - instance.$callHook(ON_LAUNCH, extend({ app: { mixin: internalInstance.appContext.app.mixin } }, options)); + instance.$callHook(ON_LAUNCH, options); }, }; initLocale(instance); diff --git a/packages/uni-mp-core/src/api/hook.ts b/packages/uni-mp-core/src/api/hook.ts deleted file mode 100644 index 945e69a83..000000000 --- a/packages/uni-mp-core/src/api/hook.ts +++ /dev/null @@ -1,19 +0,0 @@ -import { ON_LAUNCH } from '@dcloudio/uni-shared' - -import { ComponentInternalInstance, injectHook } from 'vue' - -type AppLaunchHook = (options: UniApp.LaunchOptionsApp) => void -__GLOBAL__.appLaunchHooks = [] -export function onAppLaunch(hook: AppLaunchHook) { - const app = getApp({ allowDefault: true }) - if (app && app.$vm) { - return injectHook(ON_LAUNCH, hook, app.$vm.$) - } - __GLOBAL__.appLaunchHooks.push(hook) -} - -export function injectAppLaunchHooks(appInstance: ComponentInternalInstance) { - ;(__GLOBAL__.appLaunchHooks as AppLaunchHook[]).forEach((hook) => { - injectHook(ON_LAUNCH, hook, appInstance) - }) -} diff --git a/packages/uni-mp-core/src/api/index.ts b/packages/uni-mp-core/src/api/index.ts index 2ce3194fe..076291f79 100644 --- a/packages/uni-mp-core/src/api/index.ts +++ b/packages/uni-mp-core/src/api/index.ts @@ -18,11 +18,12 @@ import { offPushMessage, invokePushCallback, } from '@dcloudio/uni-api/src/service/plugin/push' +import { invokeCreateVueAppHook, onCreateVueApp } from '@dcloudio/uni-vue' + import { promisify } from './promise' import { initWrapper } from './wrapper' import { MPProtocols } from './protocols' -import { onAppLaunch } from './hook' import { getLocale, setLocale, onLocaleChange } from './locale' const baseApis = { @@ -34,7 +35,8 @@ const baseApis = { interceptors, addInterceptor, removeInterceptor, - onAppLaunch, + onCreateVueApp, + invokeCreateVueAppHook, getLocale, setLocale, onLocaleChange, @@ -43,7 +45,6 @@ const baseApis = { offPushMessage, invokePushCallback, } - export function initUni(api: Record, protocols: MPProtocols) { const wrapper = initWrapper(protocols) const UniProxyHandlers: ProxyHandler = { diff --git a/packages/uni-mp-core/src/runtime/app.ts b/packages/uni-mp-core/src/runtime/app.ts index c2ca20dfa..47fefa764 100644 --- a/packages/uni-mp-core/src/runtime/app.ts +++ b/packages/uni-mp-core/src/runtime/app.ts @@ -16,7 +16,6 @@ import { ON_SHARE_APP_MESSAGE, } from '@dcloudio/uni-shared' -import { injectAppLaunchHooks } from '../api/hook' export interface CustomAppInstanceProperty extends Record { globalData: Record $vm?: ComponentPublicInstance @@ -61,15 +60,8 @@ export function parseApp( mpInstance: this, slots: [], }) - injectAppLaunchHooks(internalInstance) ctx.globalData = this.globalData - instance.$callHook( - ON_LAUNCH, - extend( - { app: { mixin: internalInstance.appContext.app.mixin } }, - options - ) - ) + instance.$callHook(ON_LAUNCH, options) }, } diff --git a/packages/uni-mp-kuaishou/dist/uni.api.esm.js b/packages/uni-mp-kuaishou/dist/uni.api.esm.js index c3f24e8bd..0c5ed88e6 100644 --- a/packages/uni-mp-kuaishou/dist/uni.api.esm.js +++ b/packages/uni-mp-kuaishou/dist/uni.api.esm.js @@ -1,8 +1,4 @@ import { isArray, hasOwn, isString, isPlainObject, isObject, capitalize, toRawType, makeMap, isFunction, isPromise, extend } from '@vue/shared'; -import { injectHook } from 'vue'; - -//App -const ON_LAUNCH = 'onLaunch'; const eventChannels = {}; const eventChannelStack = []; @@ -40,15 +36,6 @@ const navigateTo = { }, }; -ks.appLaunchHooks = []; -function onAppLaunch(hook) { - const app = getApp({ allowDefault: true }); - if (app && app.$vm) { - return injectHook(ON_LAUNCH, hook, app.$vm.$); - } - ks.appLaunchHooks.push(hook); -} - function getBaseSystemInfo() { return ks.getSystemInfoSync() } @@ -674,6 +661,24 @@ const offPushMessage = (fn) => { } }; +let vueApp; +const createVueAppHooks = []; +/** + * 提供 createApp 的回调事件,方便三方插件接收 App 对象,处理挂靠全局 mixin 之类的逻辑 + * @param hook + */ +function onCreateVueApp(hook) { + // TODO 每个 nvue 页面都会触发 + if (vueApp) { + return hook(vueApp); + } + createVueAppHooks.push(hook); +} +function invokeCreateVueAppHook(app) { + vueApp = app; + createVueAppHooks.forEach((hook) => hook(app)); +} + const SYNC_API_RE = /^\$|getLocale|setLocale|sendNativeEvent|restoreGlobal|getCurrentSubNVue|getMenuButtonBoundingClientRect|^report|interceptors|Interceptor$|getSubNVueById|requireNativePlugin|upx2px|hideKeyboard|canIUse|^create|Sync$|Manager$|base64ToArrayBuffer|arrayBufferToBase64/; const CONTEXT_API_RE = /^create|Manager$/; // Context例外情况 @@ -858,7 +863,8 @@ const baseApis = { interceptors, addInterceptor, removeInterceptor, - onAppLaunch, + onCreateVueApp, + invokeCreateVueAppHook, getLocale, setLocale, onLocaleChange, diff --git a/packages/uni-mp-kuaishou/dist/uni.mp.esm.js b/packages/uni-mp-kuaishou/dist/uni.mp.esm.js index 72801a0cd..1e9d51700 100644 --- a/packages/uni-mp-kuaishou/dist/uni.mp.esm.js +++ b/packages/uni-mp-kuaishou/dist/uni.mp.esm.js @@ -1,5 +1,5 @@ import { camelize, isPlainObject, isArray, hasOwn, isFunction, extend } from '@vue/shared'; -import { injectHook, ref, nextTick, findComponentPropsData, toRaw, updateProps, invalidateJob, getExposeProxy, pruneComponentPropsCache } from 'vue'; +import { ref, nextTick, findComponentPropsData, toRaw, updateProps, invalidateJob, getExposeProxy, pruneComponentPropsCache } from 'vue'; const ON_READY$1 = 'onReady'; @@ -365,13 +365,6 @@ function initRuntimeHooks(mpOptions, runtimeHooks) { }); } -ks.appLaunchHooks = []; -function injectAppLaunchHooks(appInstance) { - ks.appLaunchHooks.forEach((hook) => { - injectHook(ON_LAUNCH, hook, appInstance); - }); -} - const HOOKS = [ ON_SHOW, ON_HIDE, @@ -396,9 +389,8 @@ function parseApp(instance, parseAppOptions) { mpInstance: this, slots: [], }); - injectAppLaunchHooks(internalInstance); ctx.globalData = this.globalData; - instance.$callHook(ON_LAUNCH, extend({ app: { mixin: internalInstance.appContext.app.mixin } }, options)); + instance.$callHook(ON_LAUNCH, options); }, }; initLocale(instance); diff --git a/packages/uni-mp-lark/dist/uni.api.esm.js b/packages/uni-mp-lark/dist/uni.api.esm.js index a76038036..9edd88fc5 100644 --- a/packages/uni-mp-lark/dist/uni.api.esm.js +++ b/packages/uni-mp-lark/dist/uni.api.esm.js @@ -1,8 +1,4 @@ import { isArray, hasOwn, isString, isPlainObject, isObject, capitalize, toRawType, makeMap, isFunction, isPromise, extend } from '@vue/shared'; -import { injectHook } from 'vue'; - -//App -const ON_LAUNCH = 'onLaunch'; const eventChannels = {}; const eventChannelStack = []; @@ -40,15 +36,6 @@ const navigateTo = { }, }; -tt.appLaunchHooks = []; -function onAppLaunch(hook) { - const app = getApp({ allowDefault: true }); - if (app && app.$vm) { - return injectHook(ON_LAUNCH, hook, app.$vm.$); - } - tt.appLaunchHooks.push(hook); -} - function getBaseSystemInfo() { return tt.getSystemInfoSync() } @@ -674,6 +661,24 @@ const offPushMessage = (fn) => { } }; +let vueApp; +const createVueAppHooks = []; +/** + * 提供 createApp 的回调事件,方便三方插件接收 App 对象,处理挂靠全局 mixin 之类的逻辑 + * @param hook + */ +function onCreateVueApp(hook) { + // TODO 每个 nvue 页面都会触发 + if (vueApp) { + return hook(vueApp); + } + createVueAppHooks.push(hook); +} +function invokeCreateVueAppHook(app) { + vueApp = app; + createVueAppHooks.forEach((hook) => hook(app)); +} + const SYNC_API_RE = /^\$|getLocale|setLocale|sendNativeEvent|restoreGlobal|getCurrentSubNVue|getMenuButtonBoundingClientRect|^report|interceptors|Interceptor$|getSubNVueById|requireNativePlugin|upx2px|hideKeyboard|canIUse|^create|Sync$|Manager$|base64ToArrayBuffer|arrayBufferToBase64/; const CONTEXT_API_RE = /^create|Manager$/; // Context例外情况 @@ -858,7 +863,8 @@ const baseApis = { interceptors, addInterceptor, removeInterceptor, - onAppLaunch, + onCreateVueApp, + invokeCreateVueAppHook, getLocale, setLocale, onLocaleChange, diff --git a/packages/uni-mp-lark/dist/uni.mp.esm.js b/packages/uni-mp-lark/dist/uni.mp.esm.js index 5e27bf9f8..0c11d757a 100644 --- a/packages/uni-mp-lark/dist/uni.mp.esm.js +++ b/packages/uni-mp-lark/dist/uni.mp.esm.js @@ -1,5 +1,5 @@ import { camelize, isPlainObject, isArray, hasOwn, isFunction, extend, isObject } from '@vue/shared'; -import { injectHook, ref, nextTick, findComponentPropsData, toRaw, updateProps, invalidateJob, getExposeProxy, pruneComponentPropsCache } from 'vue'; +import { ref, nextTick, findComponentPropsData, toRaw, updateProps, invalidateJob, getExposeProxy, pruneComponentPropsCache } from 'vue'; const ON_READY$1 = 'onReady'; @@ -364,13 +364,6 @@ function initRuntimeHooks(mpOptions, runtimeHooks) { }); } -tt.appLaunchHooks = []; -function injectAppLaunchHooks(appInstance) { - tt.appLaunchHooks.forEach((hook) => { - injectHook(ON_LAUNCH, hook, appInstance); - }); -} - const HOOKS = [ ON_SHOW, ON_HIDE, @@ -395,9 +388,8 @@ function parseApp(instance, parseAppOptions) { mpInstance: this, slots: [], }); - injectAppLaunchHooks(internalInstance); ctx.globalData = this.globalData; - instance.$callHook(ON_LAUNCH, extend({ app: { mixin: internalInstance.appContext.app.mixin } }, options)); + instance.$callHook(ON_LAUNCH, options); }, }; initLocale(instance); diff --git a/packages/uni-mp-qq/dist/uni.api.esm.js b/packages/uni-mp-qq/dist/uni.api.esm.js index e29a0211c..0a467fbe8 100644 --- a/packages/uni-mp-qq/dist/uni.api.esm.js +++ b/packages/uni-mp-qq/dist/uni.api.esm.js @@ -1,8 +1,4 @@ import { isArray, hasOwn, isString, isPlainObject, isObject, capitalize, toRawType, makeMap, isFunction, isPromise, extend } from '@vue/shared'; -import { injectHook } from 'vue'; - -//App -const ON_LAUNCH = 'onLaunch'; const eventChannels = {}; const eventChannelStack = []; @@ -40,15 +36,6 @@ const navigateTo = { }, }; -qq.appLaunchHooks = []; -function onAppLaunch(hook) { - const app = getApp({ allowDefault: true }); - if (app && app.$vm) { - return injectHook(ON_LAUNCH, hook, app.$vm.$); - } - qq.appLaunchHooks.push(hook); -} - function getBaseSystemInfo() { return qq.getSystemInfoSync() } @@ -674,6 +661,24 @@ const offPushMessage = (fn) => { } }; +let vueApp; +const createVueAppHooks = []; +/** + * 提供 createApp 的回调事件,方便三方插件接收 App 对象,处理挂靠全局 mixin 之类的逻辑 + * @param hook + */ +function onCreateVueApp(hook) { + // TODO 每个 nvue 页面都会触发 + if (vueApp) { + return hook(vueApp); + } + createVueAppHooks.push(hook); +} +function invokeCreateVueAppHook(app) { + vueApp = app; + createVueAppHooks.forEach((hook) => hook(app)); +} + const SYNC_API_RE = /^\$|getLocale|setLocale|sendNativeEvent|restoreGlobal|getCurrentSubNVue|getMenuButtonBoundingClientRect|^report|interceptors|Interceptor$|getSubNVueById|requireNativePlugin|upx2px|hideKeyboard|canIUse|^create|Sync$|Manager$|base64ToArrayBuffer|arrayBufferToBase64/; const CONTEXT_API_RE = /^create|Manager$/; // Context例外情况 @@ -858,7 +863,8 @@ const baseApis = { interceptors, addInterceptor, removeInterceptor, - onAppLaunch, + onCreateVueApp, + invokeCreateVueAppHook, getLocale, setLocale, onLocaleChange, diff --git a/packages/uni-mp-qq/dist/uni.mp.esm.js b/packages/uni-mp-qq/dist/uni.mp.esm.js index 9202da6a2..c1dd2288b 100644 --- a/packages/uni-mp-qq/dist/uni.mp.esm.js +++ b/packages/uni-mp-qq/dist/uni.mp.esm.js @@ -1,5 +1,5 @@ import { camelize, isPlainObject, isArray, hasOwn, isFunction, extend } from '@vue/shared'; -import { injectHook, ref, findComponentPropsData, toRaw, updateProps, invalidateJob, getExposeProxy, pruneComponentPropsCache } from 'vue'; +import { ref, findComponentPropsData, toRaw, updateProps, invalidateJob, getExposeProxy, pruneComponentPropsCache } from 'vue'; const ON_READY$1 = 'onReady'; @@ -361,13 +361,6 @@ function initRuntimeHooks(mpOptions, runtimeHooks) { }); } -qq.appLaunchHooks = []; -function injectAppLaunchHooks(appInstance) { - qq.appLaunchHooks.forEach((hook) => { - injectHook(ON_LAUNCH, hook, appInstance); - }); -} - const HOOKS = [ ON_SHOW, ON_HIDE, @@ -392,9 +385,8 @@ function parseApp(instance, parseAppOptions) { mpInstance: this, slots: [], }); - injectAppLaunchHooks(internalInstance); ctx.globalData = this.globalData; - instance.$callHook(ON_LAUNCH, extend({ app: { mixin: internalInstance.appContext.app.mixin } }, options)); + instance.$callHook(ON_LAUNCH, options); }, }; initLocale(instance); diff --git a/packages/uni-mp-toutiao/dist/uni.api.esm.js b/packages/uni-mp-toutiao/dist/uni.api.esm.js index e37af73b2..4368b92c7 100644 --- a/packages/uni-mp-toutiao/dist/uni.api.esm.js +++ b/packages/uni-mp-toutiao/dist/uni.api.esm.js @@ -1,8 +1,4 @@ import { isArray, hasOwn, isString, isPlainObject, isObject, capitalize, toRawType, makeMap, isFunction, isPromise, extend } from '@vue/shared'; -import { injectHook } from 'vue'; - -//App -const ON_LAUNCH = 'onLaunch'; const eventChannels = {}; const eventChannelStack = []; @@ -40,15 +36,6 @@ const navigateTo = { }, }; -tt.appLaunchHooks = []; -function onAppLaunch(hook) { - const app = getApp({ allowDefault: true }); - if (app && app.$vm) { - return injectHook(ON_LAUNCH, hook, app.$vm.$); - } - tt.appLaunchHooks.push(hook); -} - function getBaseSystemInfo() { return tt.getSystemInfoSync() } @@ -674,6 +661,24 @@ const offPushMessage = (fn) => { } }; +let vueApp; +const createVueAppHooks = []; +/** + * 提供 createApp 的回调事件,方便三方插件接收 App 对象,处理挂靠全局 mixin 之类的逻辑 + * @param hook + */ +function onCreateVueApp(hook) { + // TODO 每个 nvue 页面都会触发 + if (vueApp) { + return hook(vueApp); + } + createVueAppHooks.push(hook); +} +function invokeCreateVueAppHook(app) { + vueApp = app; + createVueAppHooks.forEach((hook) => hook(app)); +} + const SYNC_API_RE = /^\$|getLocale|setLocale|sendNativeEvent|restoreGlobal|getCurrentSubNVue|getMenuButtonBoundingClientRect|^report|interceptors|Interceptor$|getSubNVueById|requireNativePlugin|upx2px|hideKeyboard|canIUse|^create|Sync$|Manager$|base64ToArrayBuffer|arrayBufferToBase64/; const CONTEXT_API_RE = /^create|Manager$/; // Context例外情况 @@ -858,7 +863,8 @@ const baseApis = { interceptors, addInterceptor, removeInterceptor, - onAppLaunch, + onCreateVueApp, + invokeCreateVueAppHook, getLocale, setLocale, onLocaleChange, diff --git a/packages/uni-mp-toutiao/dist/uni.mp.esm.js b/packages/uni-mp-toutiao/dist/uni.mp.esm.js index 3615af738..3b1a72d0c 100644 --- a/packages/uni-mp-toutiao/dist/uni.mp.esm.js +++ b/packages/uni-mp-toutiao/dist/uni.mp.esm.js @@ -1,5 +1,5 @@ import { camelize, isPlainObject, isArray, hasOwn, isFunction, extend, isObject } from '@vue/shared'; -import { injectHook, ref, nextTick, findComponentPropsData, toRaw, updateProps, invalidateJob, getExposeProxy, pruneComponentPropsCache } from 'vue'; +import { ref, nextTick, findComponentPropsData, toRaw, updateProps, invalidateJob, getExposeProxy, pruneComponentPropsCache } from 'vue'; const ON_READY$1 = 'onReady'; @@ -364,13 +364,6 @@ function initRuntimeHooks(mpOptions, runtimeHooks) { }); } -tt.appLaunchHooks = []; -function injectAppLaunchHooks(appInstance) { - tt.appLaunchHooks.forEach((hook) => { - injectHook(ON_LAUNCH, hook, appInstance); - }); -} - const HOOKS = [ ON_SHOW, ON_HIDE, @@ -395,9 +388,8 @@ function parseApp(instance, parseAppOptions) { mpInstance: this, slots: [], }); - injectAppLaunchHooks(internalInstance); ctx.globalData = this.globalData; - instance.$callHook(ON_LAUNCH, extend({ app: { mixin: internalInstance.appContext.app.mixin } }, options)); + instance.$callHook(ON_LAUNCH, options); }, }; initLocale(instance); diff --git a/packages/uni-mp-vue/dist/vue.runtime.esm.js b/packages/uni-mp-vue/dist/vue.runtime.esm.js index c2a4fee54..1e34ef59d 100644 --- a/packages/uni-mp-vue/dist/vue.runtime.esm.js +++ b/packages/uni-mp-vue/dist/vue.runtime.esm.js @@ -5251,6 +5251,9 @@ function initApp(app) { globalProperties.$set = set; globalProperties.$applyOptions = applyOptions; } + { + uni.invokeCreateVueAppHook(app); + } } const propsCaches = Object.create(null); diff --git a/packages/uni-mp-weixin/dist/uni.api.esm.js b/packages/uni-mp-weixin/dist/uni.api.esm.js index 1f84133c1..ed39b3492 100644 --- a/packages/uni-mp-weixin/dist/uni.api.esm.js +++ b/packages/uni-mp-weixin/dist/uni.api.esm.js @@ -1,17 +1,4 @@ import { isArray, hasOwn, isString, isPlainObject, isObject, capitalize, toRawType, makeMap, isFunction, isPromise, extend } from '@vue/shared'; -import { injectHook } from 'vue'; - -//App -const ON_LAUNCH = 'onLaunch'; - -wx.appLaunchHooks = []; -function onAppLaunch(hook) { - const app = getApp({ allowDefault: true }); - if (app && app.$vm) { - return injectHook(ON_LAUNCH, hook, app.$vm.$); - } - wx.appLaunchHooks.push(hook); -} function getBaseSystemInfo() { return wx.getSystemInfoSync() @@ -638,6 +625,24 @@ const offPushMessage = (fn) => { } }; +let vueApp; +const createVueAppHooks = []; +/** + * 提供 createApp 的回调事件,方便三方插件接收 App 对象,处理挂靠全局 mixin 之类的逻辑 + * @param hook + */ +function onCreateVueApp(hook) { + // TODO 每个 nvue 页面都会触发 + if (vueApp) { + return hook(vueApp); + } + createVueAppHooks.push(hook); +} +function invokeCreateVueAppHook(app) { + vueApp = app; + createVueAppHooks.forEach((hook) => hook(app)); +} + const SYNC_API_RE = /^\$|getLocale|setLocale|sendNativeEvent|restoreGlobal|getCurrentSubNVue|getMenuButtonBoundingClientRect|^report|interceptors|Interceptor$|getSubNVueById|requireNativePlugin|upx2px|hideKeyboard|canIUse|^create|Sync$|Manager$|base64ToArrayBuffer|arrayBufferToBase64/; const CONTEXT_API_RE = /^create|Manager$/; // Context例外情况 @@ -822,7 +827,8 @@ const baseApis = { interceptors, addInterceptor, removeInterceptor, - onAppLaunch, + onCreateVueApp, + invokeCreateVueAppHook, getLocale, setLocale, onLocaleChange, diff --git a/packages/uni-mp-weixin/dist/uni.mp.esm.js b/packages/uni-mp-weixin/dist/uni.mp.esm.js index e1019d9fc..5620c02e3 100644 --- a/packages/uni-mp-weixin/dist/uni.mp.esm.js +++ b/packages/uni-mp-weixin/dist/uni.mp.esm.js @@ -1,5 +1,5 @@ import { camelize, isPlainObject, isArray, hasOwn, isFunction, extend } from '@vue/shared'; -import { injectHook, ref, findComponentPropsData, toRaw, updateProps, invalidateJob, getExposeProxy, pruneComponentPropsCache } from 'vue'; +import { ref, findComponentPropsData, toRaw, updateProps, invalidateJob, getExposeProxy, pruneComponentPropsCache } from 'vue'; // quickapp-webview 不能使用 default 作为插槽名称 const SLOT_DEFAULT_NAME = 'd'; @@ -233,13 +233,6 @@ function initRuntimeHooks(mpOptions, runtimeHooks) { }); } -wx.appLaunchHooks = []; -function injectAppLaunchHooks(appInstance) { - wx.appLaunchHooks.forEach((hook) => { - injectHook(ON_LAUNCH, hook, appInstance); - }); -} - const HOOKS = [ ON_SHOW, ON_HIDE, @@ -264,9 +257,8 @@ function parseApp(instance, parseAppOptions) { mpInstance: this, slots: [], }); - injectAppLaunchHooks(internalInstance); ctx.globalData = this.globalData; - instance.$callHook(ON_LAUNCH, extend({ app: { mixin: internalInstance.appContext.app.mixin } }, options)); + instance.$callHook(ON_LAUNCH, options); }, }; initLocale(instance); diff --git a/packages/uni-quickapp-webview/dist/uni.api.esm.js b/packages/uni-quickapp-webview/dist/uni.api.esm.js index 18b318753..bf26c5c65 100644 --- a/packages/uni-quickapp-webview/dist/uni.api.esm.js +++ b/packages/uni-quickapp-webview/dist/uni.api.esm.js @@ -1,8 +1,4 @@ import { isArray, hasOwn, isString, isPlainObject, isObject, capitalize, toRawType, makeMap, isFunction, isPromise, extend } from '@vue/shared'; -import { injectHook } from 'vue'; - -//App -const ON_LAUNCH = 'onLaunch'; const eventChannels = {}; const eventChannelStack = []; @@ -40,15 +36,6 @@ const navigateTo = { }, }; -qa.appLaunchHooks = []; -function onAppLaunch(hook) { - const app = getApp({ allowDefault: true }); - if (app && app.$vm) { - return injectHook(ON_LAUNCH, hook, app.$vm.$); - } - qa.appLaunchHooks.push(hook); -} - function getBaseSystemInfo() { return qa.getSystemInfoSync() } @@ -674,6 +661,24 @@ const offPushMessage = (fn) => { } }; +let vueApp; +const createVueAppHooks = []; +/** + * 提供 createApp 的回调事件,方便三方插件接收 App 对象,处理挂靠全局 mixin 之类的逻辑 + * @param hook + */ +function onCreateVueApp(hook) { + // TODO 每个 nvue 页面都会触发 + if (vueApp) { + return hook(vueApp); + } + createVueAppHooks.push(hook); +} +function invokeCreateVueAppHook(app) { + vueApp = app; + createVueAppHooks.forEach((hook) => hook(app)); +} + const SYNC_API_RE = /^\$|getLocale|setLocale|sendNativeEvent|restoreGlobal|getCurrentSubNVue|getMenuButtonBoundingClientRect|^report|interceptors|Interceptor$|getSubNVueById|requireNativePlugin|upx2px|hideKeyboard|canIUse|^create|Sync$|Manager$|base64ToArrayBuffer|arrayBufferToBase64/; const CONTEXT_API_RE = /^create|Manager$/; // Context例外情况 @@ -858,7 +863,8 @@ const baseApis = { interceptors, addInterceptor, removeInterceptor, - onAppLaunch, + onCreateVueApp, + invokeCreateVueAppHook, getLocale, setLocale, onLocaleChange, diff --git a/packages/uni-quickapp-webview/dist/uni.mp.esm.js b/packages/uni-quickapp-webview/dist/uni.mp.esm.js index 0ba7ab08e..7b6d6f8c1 100644 --- a/packages/uni-quickapp-webview/dist/uni.mp.esm.js +++ b/packages/uni-quickapp-webview/dist/uni.mp.esm.js @@ -1,5 +1,5 @@ import { camelize, isPlainObject, isArray, hasOwn, isFunction, extend, isObject } from '@vue/shared'; -import { injectHook, ref, nextTick, findComponentPropsData, toRaw, updateProps, invalidateJob, getExposeProxy, pruneComponentPropsCache } from 'vue'; +import { ref, nextTick, findComponentPropsData, toRaw, updateProps, invalidateJob, getExposeProxy, pruneComponentPropsCache } from 'vue'; const ON_READY$1 = 'onReady'; @@ -361,13 +361,6 @@ function initRuntimeHooks(mpOptions, runtimeHooks) { }); } -qa.appLaunchHooks = []; -function injectAppLaunchHooks(appInstance) { - qa.appLaunchHooks.forEach((hook) => { - injectHook(ON_LAUNCH, hook, appInstance); - }); -} - const HOOKS = [ ON_SHOW, ON_HIDE, @@ -392,9 +385,8 @@ function parseApp(instance, parseAppOptions) { mpInstance: this, slots: [], }); - injectAppLaunchHooks(internalInstance); ctx.globalData = this.globalData; - instance.$callHook(ON_LAUNCH, extend({ app: { mixin: internalInstance.appContext.app.mixin } }, options)); + instance.$callHook(ON_LAUNCH, options); }, }; initLocale(instance); diff --git a/packages/uni-stat/dist/uni-stat.cjs.js b/packages/uni-stat/dist/uni-stat.cjs.js index 8b46b4cc6..94f11ef1d 100644 --- a/packages/uni-stat/dist/uni-stat.cjs.js +++ b/packages/uni-stat/dist/uni-stat.cjs.js @@ -937,10 +937,8 @@ function main() { if (process.env.NODE_ENV === 'development') { uni.report = function (type, options) {}; } else { - uni.onAppLaunch((options) => { - stat.report(options); - // 小程序平台此时也无法获取getApp,统一在options中传递一个app mixin对象 - options.app.mixin(lifecycle); + uni.onCreateVueApp((app) => { + app.mixin(lifecycle); uni.report = function (type, options) { stat.sendEvent(type, options); }; diff --git a/packages/uni-stat/dist/uni-stat.es.js b/packages/uni-stat/dist/uni-stat.es.js index 7596a303a..00278cb7f 100644 --- a/packages/uni-stat/dist/uni-stat.es.js +++ b/packages/uni-stat/dist/uni-stat.es.js @@ -1,11 +1,11 @@ var version = "3.0.0-alpha-3031220220222002"; -const STAT_VERSION = version; -const STAT_URL = 'https://tongji.dcloud.io/uni/stat'; -const STAT_H5_URL = 'https://tongji.dcloud.io/uni/stat.gif'; -const PAGE_PVER_TIME = 1800; -const APP_PVER_TIME = 300; -const OPERATING_TIME = 10; +const STAT_VERSION = version; +const STAT_URL = 'https://tongji.dcloud.io/uni/stat'; +const STAT_H5_URL = 'https://tongji.dcloud.io/uni/stat.gif'; +const PAGE_PVER_TIME = 1800; +const APP_PVER_TIME = 300; +const OPERATING_TIME = 10; const DIFF_TIME = 60 * 1000 * 60 * 24; const statConfig$1 = { @@ -895,12 +895,15 @@ const stat = Stat$1.getInstance(); let isHide = false; const lifecycle = { onLaunch(options) { + console.log('onLaunch') stat.report(options, this); }, onReady() { + console.log('onReady') stat.ready(this); }, onLoad(options) { + console.log('onLoad') stat.load(options, this); // 重写分享,获取分享上报事件 if (this.$scope && this.$scope.onShareAppMessage) { @@ -912,14 +915,17 @@ const lifecycle = { } }, onShow() { + console.log('onShow') isHide = false; stat.show(this); }, onHide() { + console.log('onHide') isHide = true; stat.hide(this); }, onUnload() { + console.log('onUnload') if (isHide) { isHide = false; return @@ -932,18 +938,17 @@ const lifecycle = { }; function main() { - if (process.env.NODE_ENV === 'development') { - uni.report = function (type, options) {}; - } else { - uni.onAppLaunch((options) => { - stat.report(options); - // 小程序平台此时也无法获取getApp,统一在options中传递一个app mixin对象 - options.app.mixin(lifecycle); + // if (process.env.NODE_ENV === 'development') { + // uni.report = function (type, options) {}; + // } else { + uni.onCreateVueApp((app) => { + console.log('onCreateVueApp') + app.mixin(lifecycle); uni.report = function (type, options) { stat.sendEvent(type, options); }; }); - } + // } } main(); diff --git a/packages/uni-stat/src/index.js b/packages/uni-stat/src/index.js index 17cd5d107..8e2209ba3 100644 --- a/packages/uni-stat/src/index.js +++ b/packages/uni-stat/src/index.js @@ -43,10 +43,8 @@ function main() { if (process.env.NODE_ENV === 'development') { uni.report = function (type, options) {} } else { - uni.onAppLaunch((options) => { - stat.report(options) - // 小程序平台此时也无法获取getApp,统一在options中传递一个app mixin对象 - options.app.mixin(lifecycle) + uni.onCreateVueApp((app) => { + app.mixin(lifecycle) uni.report = function (type, options) { stat.sendEvent(type, options) } diff --git a/packages/uni-vue/src/index.ts b/packages/uni-vue/src/index.ts index 4cd5ef115..0ca89412d 100644 --- a/packages/uni-vue/src/index.ts +++ b/packages/uni-vue/src/index.ts @@ -6,6 +6,9 @@ import { applyOptions } from './componentOptions' import { set } from './componentInstance' import { errorHandler, initOptionMergeStrategies } from './appConfig' import { uniIdMixin } from './uni-id-mixin' +import { invokeCreateVueAppHook } from './onCreateVueApp' + +export { onCreateVueApp, invokeCreateVueAppHook } from './onCreateVueApp' export function initApp(app: App) { const appConfig = app._context.config @@ -27,6 +30,11 @@ export function initApp(app: App) { globalProperties.$set = set globalProperties.$applyOptions = applyOptions } + if (__PLATFORM__ === 'app' || __PLATFORM__ === 'h5') { + invokeCreateVueAppHook(app) + } else { + ;(uni as any).invokeCreateVueAppHook(app) + } } export { traverse } from './reactivity' diff --git a/packages/uni-vue/src/onCreateVueApp.ts b/packages/uni-vue/src/onCreateVueApp.ts new file mode 100644 index 000000000..4f8989ab3 --- /dev/null +++ b/packages/uni-vue/src/onCreateVueApp.ts @@ -0,0 +1,21 @@ +import type { App } from 'vue' +type CreateVueAppHook = (app: App) => void + +let vueApp: App +const createVueAppHooks: CreateVueAppHook[] = [] +/** + * 提供 createApp 的回调事件,方便三方插件接收 App 对象,处理挂靠全局 mixin 之类的逻辑 + * @param hook + */ +export function onCreateVueApp(hook: CreateVueAppHook) { + // TODO 每个 nvue 页面都会触发 + if (vueApp) { + return hook(vueApp) + } + createVueAppHooks.push(hook) +} + +export function invokeCreateVueAppHook(app: App) { + vueApp = app + createVueAppHooks.forEach((hook) => hook(app)) +} -- GitLab