Menu
CoddyTech

Returning Live Refs

Part of the Fundamentals section of Coddy's Vue journey. Lesson 47 of 55.

Return a ref itself when callers need a live value. Returning its .value instead gives a snapshot at the moment the function returns.

function useLabel() {
  const label = ref('Ready');
  function reset() { label.value = 'Ready'; }
  return { label, reset };
}
const { label, reset } = useLabel();

A plain object containing refs can be destructured without losing those refs. The component can bind a returned ref with v-model, and actions in the composable still update the same object. This differs from destructuring primitive fields out of a reactive object.

challenge icon

Challenge

Medium

Complete useName.js so it returns the name ref itself, initially Neighbor, plus a reset action. The supplied app destructures the returned object, binds #name, and displays the current value inside brackets in #result. Button #reset must update both the input and display.

Try it yourself

<!doctype html><html><head><meta charset="UTF-8"><title>Vue practice</title></head><body><div id="app"></div><script type="module" src="./main.js"></script></body></html>
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Fundamentals