0
0
Vueframework~30 mins

Composable naming conventions (use prefix) in Vue - Mini Project: Build & Apply

Choose your learning style9 modes available
Composable naming conventions (use prefix)
📖 Scenario: You are building a Vue 3 application that uses composables to organize reusable logic. To keep your code clear and avoid naming conflicts, you want to follow a naming convention by adding a prefix to your composable functions.
🎯 Goal: Create a composable function with a prefix use following Vue 3 Composition API naming conventions. Then use it inside a Vue component.
📋 What You'll Learn
Create a composable function named useCounter that returns a reactive count and an increment function.
Create a Vue component that imports and uses useCounter.
Display the count and a button to increment it in the component template.
Use the setup function and ref from Vue Composition API.
💡 Why This Matters
🌍 Real World
Using composables with clear naming conventions helps keep Vue projects organized and easy to maintain, especially when sharing logic across components.
💼 Career
Understanding composable naming and usage is essential for Vue developers to write clean, reusable code and collaborate effectively in teams.
Progress0 / 4 steps
1
Create the composable function useCounter
Create a composable function named useCounter that uses Vue's ref to create a reactive variable count initialized to 0. Also create a function increment that increases count by 1. Return both count and increment from useCounter.
Vue
Need a hint?

Use ref(0) to create a reactive count variable. Define increment to add 1 to count.value. Return both in an object.

2
Import useCounter in a Vue component
In a Vue component file, import the composable function useCounter from its module. Then create a setup function where you call useCounter and get count and increment.
Vue
Need a hint?

Import useCounter and call it inside setup(). Destructure count and increment from the result and return them.

3
Add template to display count and increment button
Add a template section to the Vue component that shows the current count value and a button. When the button is clicked, it should call the increment function to increase the count.
Vue
Need a hint?

Use {{ count }} to show the count. Add a button with @click="increment" to call the increment function.

4
Complete the Vue component with script setup syntax
Convert the Vue component to use the <script setup> syntax. Import useCounter and call it directly inside <script setup>. Make sure the template uses the reactive count and the increment function.
Vue
Need a hint?

Use <script setup> to simplify the component. Import and call useCounter directly.