This is the ninth day of my participation in the First Challenge 2022. For details: First Challenge 2022.

Vue3 life cycle documents

The difference between using the life cycle in the Options API and setup

Vue3 is currently compatible with Vue2’s lifecycle functions

The mapping relationship

Options API setupThe use of
beforeCreate Don’t need
created Don’t need
beforeMount onBeforeMount
mounted onMounted
beforeUpdate onBeforeUpdate
updated onUpdated
beforeUnmount onBeforeUnmount
unmounted onUnmounted
errorCaptured onErrorCaptured
renderTracked onRenderTracked
renderTriggered onRenderTriggered
activated onActivated
deactivated onDeactivated
  • aboutsetupWhy not?beforeCreatecreatedThere is one in the official documentationtip

Because setup runs around beforeCreate and Created lifecycle hooks, there is no need to explicitly define them. In other words, any code written in these hooks should be written directly in the Setup function.

  • aboveVue3.0 source code learning – Composition APIStudy, insetupAn instance of a component when definedinstanceHas been created, therefore insetupThe use ofbeforeCreatecreatedThe hook makes no sense and confirms the official documentation

Use lifecycle hooks in Setup

import { onMounted, onUpdated, onUnmounted } from 'vue'

const MyComponent = {
  setup() {
    onMounted(() = > {
      console.log('mounted! ')
    })
    onUpdated(() = > {
      console.log('updated! ')
    })
    onUnmounted(() = > {
      console.log('unmounted! ')}}}Copy the code
  • insetupThe advantage of using lifecycle hooks in Vue2 is that you don’t have to write everything related to the same lifecycle in the lifecycle function, as Vue2 doessetupThe ability to use the same lifecycle hook function in multiple places in theComposition APIThe advantage of

The source code parsing

Look only at the lifecycle hook functions in Setup

  • How to locate source: in sourcectrl + tLook for any lifecycle hook function likeonMounted, find the source locationpackages\runtime-core\src\apiLifecycle.tsYou can see that all lifecycle hook functions execute the same functioncreateHook
export const onBeforeMount = createHook(LifecycleHooks.BEFORE_MOUNT)
export const onMounted = createHook(LifecycleHooks.MOUNTED)
export const onBeforeUpdate = createHook(LifecycleHooks.BEFORE_UPDATE)
export const onUpdated = createHook(LifecycleHooks.UPDATED)
export const onBeforeUnmount = createHook(LifecycleHooks.BEFORE_UNMOUNT)
export const onUnmounted = createHook(LifecycleHooks.UNMOUNTED)
export const onServerPrefetch = createHook(LifecycleHooks.SERVER_PREFETCH)
Copy the code

Life cycle enumeration value

  • createHookThe function entry takes a different life cycle name and returns the first argument to another functionhookThe required type is a function, which is the code that the user defines to execute in the current life cycle, eventually executing the injected hook functioninjectHook
export const createHook =
  <T extends Function = (a)= >any>(lifecycle: LifecycleHooks) => (hook: T, target: ComponentInternalInstance | null = currentInstance) => // post-create lifecycle registrations are noops during SSR (except for serverPrefetch) (! isInSSRComponentSetup || lifecycle === LifecycleHooks.SERVER_PREFETCH) && injectHook(lifecycle, hook, target)Copy the code
  • injectHookThe third parameter acceptedtargetIs the instance of the current component that will eventually be passed in by the userhookWrap a layer around it and call it at the end of the execution lifecycle
export function injectHook(
  type: LifecycleHooks,
  hook: Function& { __weh? :Function },
  target: ComponentInternalInstance | null = currentInstance,
  prepend: boolean = false
) :Function | undefined {
  if (target) {
    // Get the hooks on the instance
    const hooks = target[type] || (target[type] = [])
    // cache the error handling wrapper for injected hooks so the same hook
    // can be properly deduped by the scheduler. "__weh" stands for "with error
    // handling".
    // Wrap the hook passed in by the user
    const wrappedHook =
      hook.__weh ||
      (hook.__weh = (. args: unknown[]) = > {
        if (target.isUnmounted) {
          return
        }
        // disable tracking inside all lifecycle hooks
        // since they can potentially be called inside effects.
        pauseTracking()
        // Set currentInstance during hook invocation.
        // This assumes the hook does not synchronously trigger other hooks, which
        // can only be false when the user does something really funky.
        setCurrentInstance(target)
        // Whether an error occurs during execution
        const res = callWithAsyncErrorHandling(hook, target, type, args)
        unsetCurrentInstance()
        resetTracking()
        return res
      })
    if (prepend) {
      hooks.unshift(wrappedHook)
    } else {
      // Store the hook on the current component instance, and then execute the hook function in the future
      hooks.push(wrappedHook)
    }
    return wrappedHook
  } else if(__DEV__) { ... }}Copy the code