0
0
Vueframework~5 mins

toRef and toRefs for destructuring in Vue

Choose your learning style9 modes available
Introduction

These helpers let you easily extract parts of a reactive object so you can use them separately while keeping them reactive.

You want to use individual properties from a reactive object in your template or script.
You want to pass a single reactive property to a child component.
You want to destructure a reactive object but keep reactivity on each property.
You want to avoid losing reactivity when breaking down a reactive object.
Syntax
Vue
import { reactive, toRef, toRefs } from 'vue';

const obj = reactive({ a: 1, b: 2 });

const aRef = toRef(obj, 'a');
const { a, b } = toRefs(obj);

toRef(object, key) creates a reactive reference to one property.

toRefs(object) creates reactive references for all properties in the object.

Examples
This creates a reactive reference to count.value so you can use valueRef separately.
Vue
import { reactive, toRef } from 'vue';
const count = reactive({ value: 10 });
const valueRef = toRef(count, 'value');
This destructures state into reactive references x and y.
Vue
import { reactive, toRefs } from 'vue';
const state = reactive({ x: 5, y: 10 });
const { x, y } = toRefs(state);
Sample Program

This Vue component shows how to destructure a reactive object using toRefs. The values x and y stay reactive and update the template when changed.

Vue
<template>
  <div>
    <p>X: {{ x }}</p>
    <p>Y: {{ y }}</p>
    <button @click="x++">Increase X</button>
  </div>
</template>

<script setup>
import { reactive, toRefs } from 'vue';

const state = reactive({ x: 0, y: 0 });
const { x, y } = toRefs(state);
</script>
OutputSuccess
Important Notes

Using normal destructuring on reactive objects breaks reactivity.

toRef is useful when you want just one property as a ref.

toRefs is handy to destructure all properties at once.

Summary

toRef creates a reactive reference to a single property.

toRefs creates reactive references for all properties in an object.

Both help keep reactivity when destructuring reactive objects.