Loading...
Loading...
By continuing to use the platform, you accept the terms of the Privacy Policy and the use of cookies.
👋 Hi! I'm Dastan, author of Hack Frontend. Always open to professional networking => connect with me on LinkedIn.
Reactivity is when data changes, Vue automatically updates interface elements associated with them. This is achieved through dependency tracking system.
How Does It Work?
ref() and reactive() are used for working with reactive data.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 value count equal to 0.count.value++ — since ref() requires access through .value, we increment count value this way.count.value changes, Vue automatically updates template (template).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 object state with reactive property count.state.count++ — increment count value without .value, since reactive() works directly with objects.| 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.ref() inside reactive(), 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) }); — object state contains reactive value count created via ref().state.count.value++ — access to ref() inside reactive() requires .value.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.