QA
Intermediate LevelVue JS

How does unref() simplify utility function arguments accepting either refs or raw values?

❓ Interview Prompt: Explain unref() and Vue 3.3+ toValue() utility helpers, unwrapping ref values dynamically, and flexible composable arguments.

When writing composables or utility functions, callers might pass either a raw value ('"hello"') or a reactive ref ('ref("hello")').

'unref(val)' & 'toValue(val)' (Vue 3.3+):

•
'unref(val)': Syntactic sugar for 'isRef(val) ? val.value : val'.
•
'toValue(val)': Normalizes raw values, refs, and getter functions ('() => val') into a plain unwrapped value!

Code Implementation Example

javascript
import { unref, toValue } from 'vue';

// Utility function accepting either raw string, ref, or getter function!
function logTitle(titleInput) {
  const plainTitle = toValue(titleInput); // Normalizes input!
  console.log('Title:', plainTitle.toUpperCase());
}
💡Normalizing refs and raw values using unref() and toValue().
🎯 Interview Key Takeaway

Use unref() or toValue() inside composables to accept raw values, refs, and getter functions interchangeably.

#unref#toValue#Composables#Intermediate
Back to all Vue JS Questions→

More Vue JS Interview Questions

Beginner LevelVue JS

What is the difference between Options API and Composition API in Vue 3?

Beginner LevelVue JS

What is the difference between ref() and reactive() in Vue 3?

Beginner LevelVue JS

What is the difference between computed properties, methods, and watch/watchEffect?