From 722fec98814aec7f3d09a4db73e0ccc69d4fd1b5 Mon Sep 17 00:00:00 2001 From: fxy060608 Date: Wed, 12 Oct 2022 19:41:56 +0800 Subject: [PATCH] feat(mp): support custom lifecycle --- .../uni-mp-core/src/runtime/componentHooks.ts | 5 +++-- packages/uni-shared/src/lifecycle.ts | 21 +++++++++++++++++++ .../uni-vue/src/componentOptions/hooks.ts | 10 +++++++-- 3 files changed, 32 insertions(+), 4 deletions(-) diff --git a/packages/uni-mp-core/src/runtime/componentHooks.ts b/packages/uni-mp-core/src/runtime/componentHooks.ts index cb21271dd..0496d6416 100644 --- a/packages/uni-mp-core/src/runtime/componentHooks.ts +++ b/packages/uni-mp-core/src/runtime/componentHooks.ts @@ -1,4 +1,5 @@ import { + isUniLifecycleHook, MINI_PROGRAM_PAGE_RUNTIME_HOOKS, once, ON_ADD_TO_FAVORITES, @@ -12,7 +13,7 @@ import { ON_TAB_ITEM_TAP, ON_UNLOAD, } from '@dcloudio/uni-shared' -import { hasOwn, isArray, isFunction } from '@vue/shared' +import { hasOwn, isArray } from '@vue/shared' import { ComponentOptions } from 'vue' @@ -42,7 +43,7 @@ function findHooks( ): Set { if (vueOptions) { Object.keys(vueOptions).forEach((name) => { - if (name.indexOf('on') === 0 && isFunction(vueOptions[name])) { + if (isUniLifecycleHook(name, vueOptions[name])) { hooks.add(name) } }) diff --git a/packages/uni-shared/src/lifecycle.ts b/packages/uni-shared/src/lifecycle.ts index 8c10df49a..b11df3c70 100644 --- a/packages/uni-shared/src/lifecycle.ts +++ b/packages/uni-shared/src/lifecycle.ts @@ -1,3 +1,4 @@ +import { isFunction } from '@vue/shared' import { ON_ADD_TO_FAVORITES, ON_BACK_PRESS, @@ -95,3 +96,23 @@ export const MINI_PROGRAM_PAGE_RUNTIME_HOOKS = /*#__PURE__*/ (() => { onShareTimeline: 1 << 2, } as const })() + +export function isUniLifecycleHook( + name: string, + value: unknown, + checkType = true +) { + // 检查类型 + if (checkType && !isFunction(value)) { + return false + } + + if (UniLifecycleHooks.indexOf(name as any) > -1) { + // 已预定义 + return true + } else if (name.indexOf('on') === 0) { + // 以 on 开头 + return true + } + return false +} diff --git a/packages/uni-vue/src/componentOptions/hooks.ts b/packages/uni-vue/src/componentOptions/hooks.ts index 043279a5d..500ae614d 100644 --- a/packages/uni-vue/src/componentOptions/hooks.ts +++ b/packages/uni-vue/src/componentOptions/hooks.ts @@ -1,5 +1,10 @@ import { invokeHook } from '@dcloudio/uni-core' -import { LINEFEED, ON_LOAD, ON_SHOW } from '@dcloudio/uni-shared' +import { + isUniLifecycleHook, + LINEFEED, + ON_LOAD, + ON_SHOW, +} from '@dcloudio/uni-shared' import { isArray, isFunction } from '@vue/shared' import { @@ -31,8 +36,9 @@ export function initHooks( // 仅 App,Page 类型支持在 options 中配置 on 生命周期,组件可以使用组合式 API 定义页面生命周期 return } + Object.keys(options).forEach((name) => { - if (name.indexOf('on') === 0) { + if (isUniLifecycleHook(name, options[name], false)) { const hooks = options[name] if (isArray(hooks)) { hooks.forEach((hook) => -- GitLab