0 day streak
javascript / intermediate
Snippet

Reactivity Destructuring with toRefs

When you destructure a reactive object in Vue, the resulting variables lose their connection to the original object's reactivity. The toRefs utility converts each property of a reactive object into a corresponding ref, allowing you to destructure while maintaining a live link to the original state.

snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
import { reactive, toRefs } from 'vue';
const state = reactive({
count: 0,
user: 'Alex'
});
// Destructuring normally would lose reactivity.
// toRefs converts properties into refs.
const { count, user } = toRefs(state);
vue
Breakdown
1
const state = reactive({ ... });
Initializes a deep reactive object containing the component state.
2
toRefs(state)
Transforms the reactive object's properties into individual ref objects.
3
const { count, user } = ...
Destructures the refs so they can be used as independent variables in the template.