0
0
Vueframework~30 mins

Custom refs with customRef in Vue - Mini Project: Build & Apply

Choose your learning style9 modes available
Using Custom Refs with customRef in Vue 3
📖 Scenario: You are building a simple Vue 3 app that tracks a counter. You want to create a custom ref that logs a message every time the counter value changes.
🎯 Goal: Create a Vue 3 component that uses customRef to make a reactive counter. The counter should log a message to the console whenever its value changes.
📋 What You'll Learn
Create a reactive counter using customRef
Log a message to the console whenever the counter value changes
Display the counter value in the template
Add buttons to increment and decrement the counter
💡 Why This Matters
🌍 Real World
Custom refs let you create reactive data with special behaviors, useful for logging, debouncing, or validation in real Vue apps.
💼 Career
Understanding customRef helps you build advanced Vue components and manage reactivity beyond simple refs or reactive objects.
Progress0 / 4 steps
1
Set up the Vue component with a basic template
Create a Vue 3 component with a <template> that shows a <div> containing a <span> with the text Counter: 0. Also add two buttons labeled Increment and Decrement. Use the <script setup> block but do not add any reactive code yet.
Vue
Hint

Start by writing the HTML structure inside the <template> and add an empty <script setup> block.

2
Import customRef and create a custom reactive counter
Inside the <script setup>, import customRef from vue. Then create a variable called counter using customRef that starts at 0. For now, just return the value and a dummy setter without logging.
Vue
Hint

Use customRef with a function that returns get and set methods. Initialize the internal value to 0.

3
Add console logging inside the setter of the custom ref
Modify the set method inside the customRef so that it logs "Counter changed to: " followed by the new value to the console every time the counter changes.
Vue
Hint

Use console.log inside the set method to print the new value.

4
Bind the counter to the template and add button click handlers
Update the template so the <span> shows the reactive counter value using interpolation. Add @click handlers to the Increment and Decrement buttons that increase or decrease counter.value by 1.
Vue
Hint

Use Vue interpolation {{ counter }} to show the value. Use @click on buttons to update counter.value.