In Vue 3, the toRef
and toRefs
functions are useful for destructuring and working with reactive properties (refs) derived from props. They are particularly helpful when you need to work with props as reactive data within the setup function of a component.
toRef:
toRef
allows you to create a reference to a reactive property derived from a prop. It creates a one-way binding between the prop and the reference. If the prop changes, the reference will automatically reflect the updated value.
vue<template> <div> <!-- Using the toRef reference --> <p>{{ reactiveProp }}</p> </div> </template> <script setup> import { toRef } from 'vue'; // Props passed from the parent component const props = defineProps(['propName']); // Create a reference to the prop const reactiveProp = toRef(props, 'propName'); </script>
Benefits of
toRef
:- It allows you to work with a reactive reference to a prop without losing its reactivity.
- When the prop changes, the reference will automatically update, making your component reactive to prop changes.
toRefs:
toRefs
is used to convert an object containing reactive properties (refs) into an object where each property is a reference to the original ref. This is especially useful when you want to work with multiple reactive props simultaneously.
vue<template> <div> <!-- Using the individual toRefs --> <p>{{ prop1 }}</p> <p>{{ prop2 }}</p> </div> </template> <script setup> import { toRefs } from 'vue'; // Props passed from the parent component const props = defineProps(['prop1', 'prop2']); // Convert props object to an object of refs const { prop1, prop2 } = toRefs(props); </script>
Benefits of
toRefs
:- It allows you to work with multiple reactive props simultaneously without manually creating separate references for each prop.
- When any prop changes, the corresponding reference will update accordingly.
Using toRef
and toRefs
is especially handy when you want to work with reactive data derived from props in the setup function of a Vue 3 component. They help you maintain reactivity and ensure that your component automatically responds to changes in the props it receives from its parent component.