Performance: Reactive data with ref
This affects how efficiently Vue tracks and updates changes in reactive data, impacting rendering speed and responsiveness.
import { ref } from 'vue'; const count = ref(0); function increment() { count.value++; }
const count = reactive({ value: 0 }); function increment() { count.value++; }
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Using reactive for primitive | More proxy layers, deeper tracking | Potentially more reflows if updates cascade | Higher paint cost due to extra updates | [X] Bad |
| Using ref for primitive | Minimal proxy, direct tracking | Single reflow per update | Lower paint cost with targeted updates | [OK] Good |
ref function in Vue do?refref is used to create reactive data that Vue can track and update the UI when it changes.ref usagecount initialized to 0 using ref in Vue?ref syntaxconst count = ref(0); to create a reactive reference with initial value 0.reactive incorrectly with a primitive. let count = ref = 0; has invalid assignment syntax. var count = ref; incorrectly assigns the ref function without calling it and uses var which is discouraged in modern Vue code.import { ref } from 'vue';
const count = ref(5);
count.value++;
console.log(count.value);ref and .value usagecount is a reactive reference initialized to 5. Incrementing count.value++ increases it to 6.count.value after increment prints 6.import { ref } from 'vue';
const message = ref('Hello');
message = 'Hi';message.value = 'Hi';.ref?count with ref(0) and checks count.value < 10 before incrementing count.value++.count without .value. const count = reactive(0);
if (count.value < 10) {
count.value++;
} uses reactive with a primitive, which is incorrect. let count = ref(0);
if (count.value <= 10) {
count.value += 1;
} uses let (allowed but less preferred) and checks <= 10, which allows increment at 10, violating the condition.Pass the test and this pattern moves unknown