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

refactor: uni.onAppLaunch => uni.onCreateVueApp

上级 b5fea069
......@@ -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,
......
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)
})
}
......
......@@ -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,
......
......@@ -110,7 +110,7 @@ export {
$off,
$once,
$emit,
onAppLaunch,
onCreateVueApp,
onLocaleChange,
setPageMeta,
getEnterOptionsSync,
......
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/
......
......@@ -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<LaunchOptions, 'query' | 'scene'> {
......
......@@ -79,8 +79,8 @@
"offPushMessage",
"offWindowResize",
"onAccelerometerChange",
"onAppLaunch",
"onCompassChange",
"onCreateVueApp",
"onGyroscopeChange",
"onLocaleChange",
"onMemoryWarning",
......
......@@ -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);
......
此差异已折叠。
......@@ -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)
......
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)
}
......@@ -92,7 +92,7 @@ export {
$off,
$once,
$emit,
onAppLaunch,
onCreateVueApp,
onLocaleChange,
setPageMeta,
getEnterOptionsSync,
......
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,
......
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);
......
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,
......
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);
......
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)
})
}
......@@ -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<string, any>, protocols: MPProtocols) {
const wrapper = initWrapper(protocols)
const UniProxyHandlers: ProxyHandler<any> = {
......
......@@ -16,7 +16,6 @@ import {
ON_SHARE_APP_MESSAGE,
} from '@dcloudio/uni-shared'
import { injectAppLaunchHooks } from '../api/hook'
export interface CustomAppInstanceProperty extends Record<string, any> {
globalData: Record<string, any>
$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)
},
}
......
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,
......
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);
......
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,
......
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);
......
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,
......
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);
......
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,
......
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);
......
......@@ -5251,6 +5251,9 @@ function initApp(app) {
globalProperties.$set = set;
globalProperties.$applyOptions = applyOptions;
}
{
uni.invokeCreateVueAppHook(app);
}
}
const propsCaches = Object.create(null);
......
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,
......
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);
......
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,
......
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);
......
......@@ -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);
};
......
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();
......@@ -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)
}
......
......@@ -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'
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))
}
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册