Senior
What is the difference between ref and reactive in Vue.js?
sobes.tech AI
Answer from AI
In Vue.js, ref and reactive are two ways to create reactive data, but they have different purposes and features.
-
ref creates a reactive object with a single property
.value. It is used for primitive values (numbers, strings, booleans) or when you need to wrap a single value in reactivity.import { ref } from 'vue'; const count = ref(0); count.value++; -
reactive creates a reactive object from an object or array. It returns a proxy object that tracks changes to all nested properties.
import { reactive } from 'vue'; const state = reactive({ count: 0 }); state.count++;
Main differences:
refis used for primitives or when you need to reactively track a single value.reactiveis used for reactivity of complex objects and data structures.- When using
reffor objects, access to the value is through.value, while withreactive— directly.
In Vue 3, both approaches are often combined depending on the situation to manage reactivity effectively.