new·The score now tells you which way it movedA brain's exam only ever grows: its own material writes questions, and so does every question a real caller asked and did not get answered. The score is a percentage over that growing set, so a brain that learned more could post a smaller number — and this week three did. One of them answered two MORE questions than the week before and showed eighteen points less. Printed as a single percentage, that reads as decline to a reader and as punishment to anyone who contributes material.all news →
mozg.beta
Sign in

Vue · Tutorial · all subjects

lifecycle hooks

27 notes, read out of this brain and free to use. Each one was extracted from a source and is re-checked against its exam.

beforeCreate lifecycle hook

The beforeCreate hook is called immediately when the component instance is initialized and props are resolved, before reactive properties and state (data, computed) are set up. The setup() hook of Composition API is called before beforeCreate().

created lifecycle hook

The created hook is called after the instance has finished processing all state-related options. When created is called, reactive data, computed properties, methods, and watchers have been set up, but the mounting phase has not started and the $el property is not available yet.

beforeMount lifecycle hook

The beforeMount hook is called right before the component is mounted. The component has finished setting up its reactive state, but no DOM nodes have been created yet. It is about to execute its DOM render effect for the first time. This hook is not called during server-side rendering.

mounted lifecycle hook

The mounted hook is called after the component has been mounted. A component is considered mounted after all synchronous child components have been mounted (does not include async components or components inside <Suspense> trees) and its DOM tree has been created and inserted into the parent container. This hook is typically used for performing side effects that need access to the component's rendered DOM, or for limiting DOM-related code to the client in server-rendered applications. This hook is not called during server-side rendering.

beforeUpdate lifecycle hook

The beforeUpdate hook is called right before the component is about to update its DOM tree due to a reactive state change. This hook can be used to access the DOM state before Vue updates the DOM and it is safe to modify component state inside this hook. This hook is not called during server-side rendering.

updated lifecycle hook

The updated hook is called after the component has updated its DOM tree due to a reactive state change. A parent component's updated hook is called after that of its child components. This hook is called after any DOM update of the component, which can be caused by different state changes. If you need to access the updated DOM after a specific state change, use nextTick() instead. Do not mutate component state in the updated hook as this will likely lead to an infinite update loop. This hook is not called during server-side rendering.

beforeUnmount lifecycle hook

The beforeUnmount hook is called right before a component instance is to be unmounted. When this hook is called, the component instance is still fully functional. This hook is not called during server-side rendering.

unmounted lifecycle hook for cleanup operations

The unmounted hook is called after the component has been unmounted, after all child components have been unmounted and all associated reactive effects (render effect and computed/watchers created during setup()) have been stopped. Use this hook to clean up manually created side effects such as timers, DOM event listeners or server connections. This hook is not called during server-side rendering.

errorCaptured lifecycle hook

The errorCaptured hook is called when an error propagating from a descendant component has been captured. It receives three arguments: the error, the component instance that triggered the error, and an information string specifying the error source type. Errors can be captured from component renders, event handlers, lifecycle hooks, setup() function, watchers, custom directive hooks, and transition hooks. The hook can return false to stop the error from propagating further. By default, all errors are still sent to app.config.errorHandler if defined. If multiple errorCaptured hooks exist on a component's inheritance chain or parent chain, all will be invoked on the same error in bottom to top order, similar to DOM event bubbling. If errorCaptured hook itself throws an error, both that error and the original captured error are sent to app.config.errorHandler. Returning false prevents the error from propagating further and prevents any additional errorCaptured hooks or app.config.errorHandler from being invoked.

renderTracked lifecycle hook development-only

The renderTracked hook is called when a reactive dependency has been tracked by the component's render effect. This hook is development-mode-only and not called during server-side rendering. It receives a DebuggerEvent object with properties: effect (ReactiveEffect), target (object), type (TrackOpTypes: 'get' | 'has' | 'iterate'), and key (any).

renderTriggered lifecycle hook development-only

The renderTriggered hook is called when a reactive dependency triggers the component's render effect to be re-run. This hook is development-mode-only and not called during server-side rendering. It receives a DebuggerEvent object with properties: effect (ReactiveEffect), target (object), type (TriggerOpTypes: 'set' | 'add' | 'delete' | 'clear'), key (any), newValue (any, optional), oldValue (any, optional), and oldTarget (Map<any, any> | Set<any>, optional).

activated lifecycle hook with KeepAlive

The activated hook is called after the component instance is inserted into the DOM as part of a tree cached by <KeepAlive>. This hook is not called during server-side rendering.

deactivated lifecycle hook with KeepAlive

The deactivated hook is called after the component instance is removed from the DOM as part of a tree cached by <KeepAlive>. This hook is not called during server-side rendering.

serverPrefetch lifecycle hook SSR-only

The serverPrefetch hook is an async function to be resolved before the component instance is rendered on the server. If the hook returns a Promise, the server renderer will wait until the Promise is resolved before rendering the component. This hook is only called during server-side rendering and can be used to perform server-only data fetching.

serverPrefetch example with conditional client fetch

The serverPrefetch hook can pre-fetch data on server as it is faster than on the client. In the mounted hook, check if data is null on mount, which means the component is dynamically rendered on the client, and perform a client-side fetch instead. Example: ```js export default { data() { return { data: null } }, async serverPrefetch() { // component is rendered as part of the initial request // pre-fetch data on server as it is faster than on the client this.data = await fetchOnServer(/* ... */) }, async mounted() { if (!this.data) { // if data is null on mount, it means the component // is dynamically rendered on the client. Perform a // client-side fetch instead. this.data = await fetchOnClient(/* ... */) } } } ```

onMounted hook in Composition API

The onMounted lifecycle hook runs code after the component has finished initial rendering and created the DOM nodes. In Composition API, import onMounted from 'vue' and call it with a callback function in <script setup>.

mounted hook in Options API

The mounted lifecycle hook runs code after the component has finished initial rendering and created the DOM nodes. In Options API, define it as a method in the component object.

Commonly used lifecycle hooks - Composition API

The most commonly used lifecycle hooks in Composition API are onMounted, onUpdated, and onUnmounted.

Commonly used lifecycle hooks - Options API

The most commonly used lifecycle hooks in Options API are mounted, updated, and unmounted.

Arrow functions in Options API lifecycle hooks

In Options API, you should avoid using arrow functions when declaring lifecycle hooks because you won't be able to access the component instance via 'this' if you do so. Lifecycle hooks are called with their 'this' context pointing to the current active instance invoking it.

Synchronous registration requirement for Composition API lifecycle hooks

Lifecycle hooks in Composition API must be registered synchronously during component setup. Vue automatically associates the registered callback function with the current active component instance. Do not call onMounted or other lifecycle hooks inside setTimeout or other async operations. However, onMounted can be called in an external function as long as the call stack is synchronous and originates from within setup().

onMounted hook example - Composition API

Example of using onMounted in Composition API: import { onMounted } from 'vue'; onMounted(() => { console.log(`the component is now mounted.`) })

mounted hook example - Options API

Example of using mounted in Options API: export default { mounted() { console.log(`the component is now mounted.`) } }

onUnmounted hook for cleanup operations

The onUnmounted lifecycle hook is one of the commonly used hooks and is available for cleanup operations when a component is being unmounted.

Vue component lifecycle stages

Each Vue component instance goes through a series of initialization steps when it's created, including setting up data observation, compiling the template, mounting the instance to the DOM, and updating the DOM when data changes. Lifecycle hooks run at different stages to allow users to add their own code.

Creating stateful methods in created() hook

To keep each component instance's debounced function independent, create the debounced version in the `created` lifecycle hook. This ensures each instance has its own copy of the handler. Also cancel the timer in the `unmounted` hook when the component is removed.

Debounced method example in created() hook

import { debounce } from 'lodash-es' export default { created() { // each instance now has its own copy of debounced handler this.debouncedClick = debounce(this.click, 500) }, unmounted() { // also a good idea to cancel the timer // when the component is removed this.debouncedClick.cancel() }, methods: { click() { // ... respond to click ... } } }

Give your agent this brain