Bird
Raised Fist0
Vueframework~15 mins

Setup function basics in Vue - Deep Dive

Choose your learning style10 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.

Practice

(1/5)
1. What is the main purpose of the setup function in a Vue 3 component?
easy
A. To register global components
B. To define reactive data and functions before the component renders
C. To handle routing between pages
D. To style the component using CSS

Solution

  1. Step 1: Understand the role of setup in Vue 3

    The setup function is where you declare reactive data and functions that the component will use.
  2. Step 2: Compare with other options

    Styling, routing, and global registration are handled elsewhere, not in setup.
  3. Final Answer:

    To define reactive data and functions before the component renders -> Option B
  4. Quick Check:

    Setup function = reactive data + functions [OK]
Hint: Remember: setup is for data and logic, not styling or routing [OK]
Common Mistakes:
  • Confusing setup with styling or routing
  • Thinking setup runs after rendering
  • Assuming setup registers global components
2. Which of the following is the correct way to declare a reactive variable inside the setup function using Vue 3 Composition API?
easy
A. const count = useState(0);
B. const count = reactive(0);
C. const count = reactive({ value: 0 });
D. const count = ref(0);

Solution

  1. Step 1: Identify correct reactive declaration for simple values

    For simple reactive variables like numbers, ref is used, e.g., const count = ref(0);.
  2. Step 2: Check other options

    reactive is for objects, not primitives; useState is not a Vue function.
  3. Final Answer:

    const count = ref(0); -> Option D
  4. Quick Check:

    Simple reactive variable = ref() [OK]
Hint: Use ref() for single values, reactive() for objects [OK]
Common Mistakes:
  • Using reactive() for primitive values
  • Trying to use non-existent useState()
  • Wrapping primitive in reactive({ value: ... }) unnecessarily
3. Consider this Vue 3 component setup code:
import { ref } from 'vue';

export default {
  setup() {
    const message = ref('Hello');
    function update() {
      message.value = 'Hi';
    }
    return { message, update };
  }
}

What will be the value of message after calling update()?
medium
A. 'Hi'
B. undefined
C. 'Hello'
D. An error occurs

Solution

  1. Step 1: Understand ref and updating its value

    message is a ref holding 'Hello'. Calling update() sets message.value to 'Hi'.
  2. Step 2: Determine final value after update

    After update(), message.value is 'Hi', so message reactive variable reflects 'Hi'.
  3. Final Answer:

    'Hi' -> Option A
  4. Quick Check:

    Ref value updated correctly = 'Hi' [OK]
Hint: Remember to access .value to update ref variables [OK]
Common Mistakes:
  • Forgetting to use .value to update ref
  • Assuming message itself changes, not message.value
  • Thinking update() does not affect message
4. Identify the error in this Vue 3 setup function:
import { ref } from 'vue';

export default {
  setup() {
    const count = ref(0);
    function increment() {
      count = count + 1;
    }
    return { count, increment };
  }
}
medium
A. setup function should return a single object
B. Missing import of reactive
C. Cannot assign to ref variable directly; should use count.value
D. increment function is not declared correctly

Solution

  1. Step 1: Check how ref variables are updated

    Ref variables hold their value inside .value. Direct assignment like count = count + 1 is invalid.
  2. Step 2: Correct way to update ref

    Use count.value = count.value + 1 or count.value++ to update.
  3. Final Answer:

    Cannot assign to ref variable directly; should use count.value -> Option C
  4. Quick Check:

    Update ref with .value [OK]
Hint: Always update ref with .value, not direct assignment [OK]
Common Mistakes:
  • Assigning directly to ref variable
  • Forgetting to use .value when updating
  • Confusing reactive and ref update syntax
5. You want to create a Vue 3 component using <script setup> that has a reactive object with properties name and age. Which code correctly defines this reactive object and updates age by 1 inside setup?
hard
A.
import { reactive } from 'vue';

const person = reactive({ name: 'Alice', age: 30 });
person.age++;
B.
import { ref } from 'vue';

const person = ref({ name: 'Alice', age: 30 });
person.age++;
C.
import { reactive } from 'vue';

const person = reactive({ name: 'Alice', age: 30 });
person = { ...person, age: person.age + 1 };
D.
import { ref } from 'vue';

const person = ref({ name: 'Alice', age: 30 });
person.value.age = person.age + 1;

Solution

  1. Step 1: Choose correct reactive type for object

    Use reactive for objects to make all properties reactive.
  2. Step 2: Update property correctly

    With reactive, update properties directly like person.age++. Using ref with objects requires accessing .value.
  3. Final Answer:

    import { reactive } from 'vue'; const person = reactive({ name: 'Alice', age: 30 }); person.age++; -> Option A
  4. Quick Check:

    Reactive object updated directly =
    import { reactive } from 'vue';
    
    const person = reactive({ name: 'Alice', age: 30 });
    person.age++;
    
    [OK]
Hint: Use reactive() for objects, update properties directly [OK]
Common Mistakes:
  • Using ref for objects without .value access
  • Reassigning reactive object instead of updating property
  • Trying to increment property on ref object without .value
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard