Explain how reactivity works in Vue 3: reactive, ref, shallowReactive, markRaw.
sobes.tech AI
Answer from AI
In Vue 3, reactivity is implemented through the Composition API using functions like reactive, ref, shallowReactive, and markRaw.
-
reactive(obj)— creates a reactive proxy for the objectobj. All nested properties become reactive, changes are tracked, and component updates are triggered. -
ref(value)— creates a reactive object with a single property.value. Used for primitive values (numbers, strings) or when you need to reactively track a single value. -
shallowReactive(obj)— creates a reactive proxy, but only at the first level. Nested objects are not reactive, which is useful for optimization if deep reactivity is not needed. -
markRaw(obj)— marks an object as "raw", meaning Vue will not make it reactive. Used for objects that should not be tracked, such as third-party libraries or large data structures.
Example:
import { reactive, ref, shallowReactive, markRaw } from 'vue';
const state = reactive({
count: 0,
nested: { value: 10 }
});
const number = ref(5);
const shallow = shallowReactive({ nested: { value: 20 } });
const rawObj = markRaw(new Map());
state.count++; // reactive
number.value = 10; // reactive
shallow.nested.value = 30; // NOT reactive
rawObj.set('key', 'value'); // Vue does not track changes