Performance: Setup function basics
This affects the initial rendering speed and reactivity setup of Vue components.
import { reactive, computed } from 'vue'; export default { setup() { const state = reactive({ count: 0 }); const doubled = computed(() => state.count * 2); return { state, doubled }; } }
import { reactive, computed } from 'vue'; export default { setup() { const state = reactive({ count: 0 }); const doubled = computed(() => { // heavy computation inside computed let result = 0; for (let i = 0; i < 1000000; i++) { result += state.count * 2; } return result; }); return { state, doubled }; } }
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Heavy computation in setup | Minimal | 0 | High due to JS blocking | [X] Bad |
| Simple reactive state in setup | Minimal | 0 | Low | [OK] Good |
| Data fetching inside setup | Minimal | 0 | Blocks LCP until data arrives | [X] Bad |
| Data fetching in onMounted hook | Minimal | 0 | Non-blocking initial paint | [OK] Good |
setup function in a Vue 3 component?setup in Vue 3setup function is where you declare reactive data and functions that the component will use.setup.setup function using Vue 3 Composition API?ref is used, e.g., const count = ref(0);.reactive is for objects, not primitives; useState is not a Vue function.import { ref } from 'vue';
export default {
setup() {
const message = ref('Hello');
function update() {
message.value = 'Hi';
}
return { message, update };
}
}message after calling update()?message is a ref holding 'Hello'. Calling update() sets message.value to 'Hi'.update(), message.value is 'Hi', so message reactive variable reflects 'Hi'.setup function:import { ref } from 'vue';
export default {
setup() {
const count = ref(0);
function increment() {
count = count + 1;
}
return { count, increment };
}
}.value. Direct assignment like count = count + 1 is invalid.count.value = count.value + 1 or count.value++ to update.<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?reactive for objects to make all properties reactive.reactive, update properties directly like person.age++. Using ref with objects requires accessing .value.import { reactive } from 'vue';
const person = reactive({ name: 'Alice', age: 30 });
person.age++;
[OK]Pass the test and this pattern moves unknown