0
0
Vueframework~30 mins

Why composables matter in Vue - See It in Action

Choose your learning style9 modes available
Why composables matter
📖 Scenario: You are building a simple Vue 3 app that tracks a user's online status. You want to reuse this online status logic in multiple components without repeating code.
🎯 Goal: Create a composable function to manage online status and use it inside a Vue component to display if the user is online or offline.
📋 What You'll Learn
Create a composable function called useOnlineStatus that returns a reactive isOnline variable
Add a configuration variable checkInterval inside the composable to set how often to check the online status
Use setInterval inside the composable to update isOnline every checkInterval milliseconds
Create a Vue component that uses useOnlineStatus and shows Online or Offline text based on isOnline
💡 Why This Matters
🌍 Real World
Many apps need to know if the user is online or offline to adjust behavior, like disabling buttons or showing warnings.
💼 Career
Understanding composables helps you write clean, reusable Vue 3 code, a key skill for frontend developer roles.
Progress0 / 4 steps
1
Create the composable function
Create a composable function called useOnlineStatus that imports ref from 'vue' and defines a reactive variable isOnline initialized to navigator.onLine.
Vue
Need a hint?

Use ref to create a reactive variable and initialize it with navigator.onLine.

2
Add a check interval variable
Inside the useOnlineStatus function, add a constant checkInterval and set it to 5000 (milliseconds).
Vue
Need a hint?

Just add a constant named checkInterval with value 5000 inside the function.

3
Update online status periodically
Inside useOnlineStatus, use setInterval with checkInterval to update isOnline.value to navigator.onLine every interval.
Vue
Need a hint?

Use setInterval to update isOnline.value inside the callback function.

4
Use the composable in a Vue component
Create a Vue component using <script setup> that imports useOnlineStatus, calls it, and displays Online if isOnline.value is true, else Offline inside a <p> tag.
Vue
Need a hint?

Use useOnlineStatus inside <script setup> and bind isOnline in the template with a conditional text.