Middle
What is the difference between ref and reactive in Vue?
sobes.tech AI
Answer from AI
In Vue 3, ref and reactive are two ways to create reactive data, but they are used in different cases:
-
refcreates a reactive object that contains a single primitive value or object. To access the value, you need to use the.valueproperty. This is convenient for simple data types (numbers, strings, booleans) or when you need to wrap a single value. -
reactivecreates a reactive object from an object or array, allowing you to track changes to its properties directly without.value.
Example:
import { ref, reactive } from 'vue';
const count = ref(0); // number, accessed via count.value
const state = reactive({
name: 'Vue',
items: [1, 2, 3]
});
count.value++;
state.name = 'Vue 3';
state.items.push(4);
Summary:
reffor primitives or single valuesreactivefor objects and arrays
Both create reactive data that Vue tracks for UI updates.