How Does Reactivity Work in Vue.js?
What is Reactivity?
Reactivity is when data changes, Vue automatically updates interface elements associated with them. This is achieved through dependency tracking system.
How Does It Work?
- Vue tracks changes in reactive variables.
- When value changes, components depending on it automatically re-render.
ref()andreactive()are used for working with reactive data.
ref()
ref() is used to create reactive values. It's suitable for working with primitives (numbers, strings, booleans) and objects.
ref() Usage Example
<script setup>
import { ref } from 'vue';
const count = ref(0);
const increment = () => {
count.value++;
};
</script>
count = ref(0);— create reactive valuecountequal to 0.count.value++— sinceref()requires access through.value, we incrementcountvalue this way.- When
count.valuechanges, Vue automatically updates template (template).
reactive()
reactive() is used to create reactive objects and arrays.
reactive() Usage Example
<script setup>
import { reactive } from 'vue';
const state = reactive({ count: 0 });
const increment = () => {
state.count++;
};
</script>
state = reactive({ count: 0 });— create objectstatewith reactive propertycount.state.count++— incrementcountvalue without.value, sincereactive()works directly with objects.- Vue automatically tracks changes and updates interface.
Difference Between ref() and reactive()
| Criterion | ref() | reactive() |
|---|---|---|
| Primitive support | Yes | No |
| Object support | Yes | Yes |
| Value access | Through .value | Direct access |
| Deep reactivity | Yes | Yes |
| Structure change | Easy (can assign new value) | Cannot (structure is fixed) |
When to Use?
ref()— if you need to work with primitives.reactive()— if you need to create reactive object.- Combination — can use
ref()insidereactive(), if you need to store primitive values in reactive object.
Combined Approach Example:
<script setup>
import { reactive, ref } from 'vue';
const state = reactive({
count: ref(0)
});
const increment = () => {
state.count.value++;
};
</script>
state = reactive({ count: ref(0) });— objectstatecontains reactive valuecountcreated viaref().state.count.value++— access toref()insidereactive()requires.value.- This approach is convenient if part of data in object should be primitives with ability to assign new value.
Summary
Vue.js provides two powerful mechanisms for working with reactive data:
ref()— for primitive values and objects with access through.value.reactive()— for working with objects and arrays without.value.
Both methods can be combined depending on project requirements. Choice depends on data structure and convenience of working with them.