Middle
What is the difference between ref and reactive in Vue 3?
sobes.tech AI
Answer from AI
In Vue 3, ref and reactive are two ways to create reactive data, but they differ in purpose and the types of data they work with.
-
refis used to create a reactive object that contains a primitive value or an object in its.valueproperty. It is a wrapper around the value that allows tracking its changes. -
reactivecreates a reactive proxy object from the passed object, allowing direct tracking of changes to its properties.
Example:
import { ref, reactive } from 'vue';
const count = ref(0); // reactive primitive value
count.value++;
const state = reactive({
count: 0
});
state.count++;
Key differences:
refis suitable for primitives (numbers, strings, booleans) and when you need to reactively track a single value.reactiveis better for objects and arrays to make all their properties reactive.
In Vue templates, ref is automatically unwrapped, so you can just write {{ count }}, but in code, you need to access .value.
Summary:
- Use
reffor simple values or when you need reactivity of a single value. - Use
reactivefor complex objects with multiple properties.