0
0
Vueframework~15 mins

Setup function basics in Vue - Deep Dive

Choose your learning style9 modes available
Overview - Setup function basics
What is it?
The setup function is a special part of Vue 3 components where you write the logic that controls the component's behavior. It runs before the component is created and lets you define reactive data, functions, and computed properties in one place. This function replaces some older ways of writing components and makes your code clearer and easier to manage. It is the heart of Vue's Composition API.
Why it matters
Without the setup function, Vue components would rely on older, more scattered ways to manage data and behavior, making code harder to read and reuse. The setup function solves this by centralizing logic, improving code organization, and enabling better reuse of functionality across components. This makes building and maintaining apps faster and less error-prone.
Where it fits
Before learning the setup function, you should understand basic Vue components and reactive data concepts. After mastering setup, you can explore advanced Composition API features like custom composables, lifecycle hooks inside setup, and Vue's reactivity system in depth.
Mental Model
Core Idea
The setup function is the starting point where you declare all the reactive data and functions that your Vue component will use, before the component is created.
Think of it like...
Think of the setup function like packing your backpack before a trip: you decide what tools, snacks, and maps you need and organize them neatly so you can easily use them during your journey.
┌─────────────────────────────┐
│ Vue Component               │
│ ┌─────────────────────────┐ │
│ │ setup()                 │ │
│ │ ┌─────────────────────┐ │ │
│ │ │ Declare reactive     │ │ │
│ │ │ data & functions     │ │ │
│ │ └─────────────────────┘ │ │
│ │ Returns data & methods  │ │
│ └─────────────────────────┘ │
│ Component uses returned data │
└─────────────────────────────┘
Build-Up - 7 Steps
1
FoundationWhat is the setup function
🤔
Concept: Introduction to the setup function as the entry point for component logic in Vue 3.
In Vue 3, the setup function is a new way to write components. It runs before the component is created and lets you define reactive data and functions. Instead of spreading logic across different options like data, methods, and computed, you put them all inside setup. This makes your code easier to understand and reuse.
Result
You understand that setup is where you start writing your component's logic in Vue 3.
Knowing that setup centralizes component logic helps you write cleaner and more maintainable Vue components.
2
FoundationReturning data from setup
🤔
Concept: How to expose reactive data and functions from setup to the template.
Inside setup, you create reactive variables using Vue's reactive or ref functions. To make these variables and functions usable in the component's template, you return them from setup as an object. Vue then makes these properties available in the template for rendering or event handling.
Result
Reactive data and functions declared in setup become accessible in the component's template.
Understanding the return object from setup is key to connecting your logic with the component's visible UI.
3
IntermediateUsing reactive and ref inside setup
🤔Before reading on: do you think reactive and ref create the same kind of reactive data? Commit to your answer.
Concept: Learn the difference between reactive and ref for creating reactive state inside setup.
Vue provides two ways to create reactive data inside setup: reactive and ref. reactive wraps an object to make all its properties reactive, while ref creates a reactive reference to a simple value like a number or string. You use ref for single values and reactive for objects or arrays. Accessing ref values requires .value, but reactive objects behave like normal objects.
Result
You can create reactive state correctly inside setup using reactive or ref depending on your data type.
Knowing when to use reactive versus ref prevents bugs and makes your reactive state easier to work with.
4
IntermediateSetup function lifecycle timing
🤔Before reading on: does setup run before or after the component is created? Commit to your answer.
Concept: Understand when setup runs in the component lifecycle and what that means for your code.
The setup function runs before the component instance is fully created. This means you cannot access this or component properties inside setup. Instead, you use the arguments passed to setup or Vue's reactive APIs. This early timing allows Vue to collect reactive dependencies before rendering.
Result
You know setup runs early and what limitations that imposes.
Understanding setup's timing helps avoid common mistakes like trying to access this or lifecycle hooks too early.
5
IntermediateUsing props and context in setup
🤔Before reading on: do you think props inside setup are reactive or static? Commit to your answer.
Concept: Learn how to access component props and context inside setup and their reactivity.
Setup receives props as the first argument and a context object as the second. Props inside setup are reactive, so if the parent changes a prop, your setup code sees the update. The context object gives access to attrs, slots, and emit for events. This replaces older ways of accessing these features.
Result
You can use props and context inside setup to build dynamic components.
Knowing props are reactive inside setup lets you respond to changes smoothly and use context for advanced features.
6
AdvancedAvoiding common setup pitfalls
🤔Before reading on: can you use this inside setup? Commit to your answer.
Concept: Identify common mistakes like using this inside setup and how to avoid them.
Inside setup, this is undefined because the component instance is not created yet. Trying to use this leads to errors. Instead, use the props argument or Vue's reactive APIs. Also, avoid side effects that depend on DOM elements inside setup; use lifecycle hooks like onMounted for that.
Result
You avoid errors caused by misusing this or accessing DOM too early.
Understanding setup's context prevents frustrating bugs and guides proper reactive programming.
7
ExpertSetup function and reactivity tracking internals
🤔Before reading on: do you think Vue tracks dependencies automatically inside setup? Commit to your answer.
Concept: Explore how Vue tracks reactive dependencies declared inside setup for efficient updates.
When you create reactive data inside setup, Vue wraps it with proxies that track which parts your template or functions use. When reactive data changes, Vue knows exactly what to update. This automatic tracking happens because setup runs before rendering, letting Vue collect dependencies precisely. This system avoids unnecessary updates and keeps UI fast.
Result
You understand the powerful reactivity system working behind setup's simple code.
Knowing Vue's dependency tracking inside setup reveals why Composition API is both flexible and performant.
Under the Hood
The setup function runs before the component instance is created. Vue calls setup with props and context, then collects the returned object. Vue wraps reactive data with proxies to track dependencies. When reactive data changes, Vue triggers updates only where needed. Setup's early execution allows Vue to build a precise dependency graph for efficient rendering.
Why designed this way?
Vue 3 introduced setup to solve problems with the Options API, where logic was scattered and hard to reuse. Setup centralizes logic, improves type inference, and enables better code reuse. The design favors explicit reactive declarations and early dependency tracking for performance and clarity.
┌───────────────┐
│ Vue Component │
└──────┬────────┘
       │ calls setup(props, context)
       ▼
┌─────────────────────┐
│ setup function runs  │
│ - declares reactive  │
│ - returns object     │
└─────────┬───────────┘
          │ Vue wraps reactive data with proxies
          ▼
┌─────────────────────┐
│ Vue collects deps    │
│ and renders template │
└─────────┬───────────┘
          │ reactive changes trigger updates
          ▼
┌─────────────────────┐
│ UI updates efficiently│
└─────────────────────┘
Myth Busters - 4 Common Misconceptions
Quick: Can you use this inside the setup function? Commit to yes or no.
Common Belief:You can use this inside setup just like in other component options.
Tap to reveal reality
Reality:Inside setup, this is undefined because the component instance is not created yet.
Why it matters:Using this inside setup causes runtime errors and confusion, blocking component logic.
Quick: Are props inside setup reactive or static? Commit to your answer.
Common Belief:Props inside setup are static and do not update if the parent changes them.
Tap to reveal reality
Reality:Props inside setup are reactive and update when the parent changes them.
Why it matters:Assuming props are static leads to stale data and bugs in dynamic components.
Quick: Does returning data from setup automatically make it reactive? Commit to yes or no.
Common Belief:Returning plain objects from setup makes them reactive automatically.
Tap to reveal reality
Reality:Only reactive or ref-wrapped data is reactive; plain objects are not reactive by default.
Why it matters:Not wrapping data properly causes UI not to update when data changes.
Quick: Does setup run after the component is mounted? Commit to yes or no.
Common Belief:Setup runs after the component is mounted and DOM is ready.
Tap to reveal reality
Reality:Setup runs before mounting; DOM is not available yet inside setup.
Why it matters:Trying to access DOM elements inside setup causes errors or undefined behavior.
Expert Zone
1
Reactive refs returned from setup are unwrapped automatically in templates but require .value access in JavaScript code.
2
Setup can return functions directly, enabling advanced patterns like render functions or exposing methods to parent components.
3
Using the context argument in setup allows fine control over attributes, slots, and event emission without relying on this.
When NOT to use
Setup is not ideal for very simple components where Options API is clearer. Also, if you need to access component instance properties or lifecycle hooks outside setup, Options API or script setup syntax might be better. For legacy Vue 2 projects, setup is unavailable.
Production Patterns
In real apps, setup is used with composables—reusable functions that encapsulate logic and state. Setup also works with TypeScript for strong typing. Developers often combine setup with script setup syntax for concise components and use setup to organize complex logic cleanly.
Connections
Reactive Programming
Setup function uses reactive programming principles to track and update UI automatically.
Understanding reactive programming helps grasp how setup manages data changes and UI updates efficiently.
Functional Programming
Setup encourages writing functions that return data and behavior, similar to pure functions in functional programming.
Knowing functional programming concepts clarifies why setup returns objects and avoids side effects early.
Cooking Recipe Preparation
Setup is like preparing ingredients before cooking, organizing everything needed before the main process.
This connection shows how setup organizes component logic upfront, making the rendering process smoother.
Common Pitfalls
#1Trying to use this inside setup causes errors.
Wrong approach:setup() { console.log(this.someData); return {}; }
Correct approach:setup(props) { console.log(props.someData); return {}; }
Root cause:Misunderstanding that setup runs before component instance creation, so this is undefined.
#2Returning plain objects without reactive wrappers causes no UI updates.
Wrong approach:setup() { const count = 0; return { count }; }
Correct approach:import { ref } from 'vue'; setup() { const count = ref(0); return { count }; }
Root cause:Not using ref or reactive to make data reactive inside setup.
#3Accessing DOM elements inside setup leads to undefined references.
Wrong approach:setup() { const el = document.getElementById('myDiv'); console.log(el); return {}; }
Correct approach:import { onMounted, ref } from 'vue'; setup() { const el = ref(null); onMounted(() => { console.log(el.value); }); return { el }; }
Root cause:Setup runs before DOM is rendered; DOM access must wait until mounted.
Key Takeaways
The setup function is the central place to declare reactive data and functions in Vue 3 components.
Data and functions must be returned from setup to be accessible in the template.
Use ref for simple reactive values and reactive for objects or arrays inside setup.
Setup runs before the component instance is created, so this is undefined and DOM is not ready.
Understanding setup's reactivity and lifecycle timing is essential to avoid common mistakes and write clean Vue components.