Performance: Why the Composition API exists
This affects how Vue components load and update, impacting rendering speed and responsiveness.
import { ref, watch } from 'vue'; export default { setup() { const count = ref(0); function increment() { count.value++; } watch(count, (newVal) => { console.log('Count changed:', newVal); }); return { count, increment }; } }
export default { data() { return { count: 0 }; }, methods: { increment() { this.count++; } }, watch: { count(newVal) { console.log('Count changed:', newVal); } } }
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Options API scattered logic | More reactive dependencies | Multiple re-renders | Higher paint cost due to redundant updates | [X] Bad |
| Composition API grouped logic | Fewer reactive dependencies | Single targeted re-render | Lower paint cost with precise updates | [OK] Good |
ref function from Vue's Composition API?setup()?
import { ref } from 'vue';
export default {
setup() {
const count = ref(0);
count.value++;
return { count };
}
}
What is the value of count when rendered?ref(0) creates a reactive object with initial value 0 accessible via count.value.count.value++ increases the value from 0 to 1 before returning it.import { reactive } from 'vue';
export default {
setup() {
const state = reactive({ count: 0 });
function increment() {
state.count += 1
}
return { state, increment };
}
}reactive function creates a reactive object whose properties can be mutated directly.state.count correctly without syntax errors.Pass the test and this pattern moves unknown