componentLifecycle.ts 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. import { ComponentInstance, LifecycleHooks, currentInstance } from './component'
  2. function injectHook(
  3. name: keyof LifecycleHooks,
  4. hook: () => void,
  5. target: ComponentInstance | null | void = currentInstance
  6. ) {
  7. if (target) {
  8. const existing = target[name]
  9. // TODO inject a error-handling wrapped version of the hook
  10. if (existing !== null) {
  11. existing.push(hook)
  12. } else {
  13. target[name] = [hook]
  14. }
  15. } else {
  16. // TODO warn
  17. }
  18. }
  19. export function onBeforeMount(hook: () => void, target?: ComponentInstance) {
  20. injectHook('bm', hook, target)
  21. }
  22. export function onMounted(hook: () => void, target?: ComponentInstance) {
  23. injectHook('m', hook, target)
  24. }
  25. export function onBeforeUpdate(hook: () => void, target?: ComponentInstance) {
  26. injectHook('bu', hook, target)
  27. }
  28. export function onUpdated(hook: () => void, target?: ComponentInstance) {
  29. injectHook('u', hook, target)
  30. }
  31. export function onBeforeUnmount(hook: () => void, target?: ComponentInstance) {
  32. injectHook('bum', hook, target)
  33. }
  34. export function onUnmounted(hook: () => void, target?: ComponentInstance) {
  35. injectHook('um', hook, target)
  36. }
  37. export function onRenderTriggered(
  38. hook: () => void,
  39. target?: ComponentInstance
  40. ) {
  41. injectHook('rtg', hook, target)
  42. }
  43. export function onRenderTracked(hook: () => void, target?: ComponentInstance) {
  44. injectHook('rtc', hook, target)
  45. }
  46. export function onErrorCaptured(hook: () => void, target?: ComponentInstance) {
  47. injectHook('ec', hook, target)
  48. }