What is unref in Vue: Simple Explanation and Usage
unref in Vue is a helper function that returns the inner value of a reactive reference or the value itself if it is not reactive. It helps you easily get the raw value from a ref without manually accessing the .value property.How It Works
Imagine you have a box labeled "ref" that holds a value inside. Normally, to get the value, you have to open the box by writing .value. unref is like a helper that opens the box for you if it is a ref, or just hands you the value directly if it is not a ref.
This makes your code cleaner because you don't have to check if something is a ref or a plain value before using it. unref handles that check internally and always gives you the actual value.
Example
This example shows how unref works with both a ref and a normal value.
import { ref, unref } from 'vue' const countRef = ref(5) const normalValue = 10 console.log(unref(countRef)) // Outputs 5 console.log(unref(normalValue)) // Outputs 10
When to Use
Use unref when you want to write functions or code that can accept either reactive refs or plain values without extra checks. For example, in utility functions or computed properties where inputs might be refs or normal values.
This helps keep your code simple and flexible, especially when working with Vue's reactivity system.
Key Points
unrefreturns the inner value of a ref or the value itself if not a ref.- It simplifies code by avoiding manual
.valueaccess. - Useful in functions that accept both refs and normal values.
- Part of Vue 3's Composition API.
Key Takeaways
unref extracts the value from a ref or returns the value directly if not a ref..value manually.unref in functions that accept both reactive and non-reactive inputs.unref is part of Vue 3's Composition API and improves reactivity handling.