Reusable methods that can be use in any pages

How to make reusable methods and that can be used in any pages. Please make it for the most best practice of it.
1 Reply
kapa.ai
kapa.ai2mo ago
Hi @Adnan Erlansyah. I'm kapa.ai, your friendly support bot. I will try to answer your question by searching through the knowledge base. :wave: ---------------------- To create reusable methods that can be used across any pages in a Nuxt application, the best practice is to utilize the utils/ directory. This approach allows you to create utility functions that are automatically imported and available throughout your application. Here's how you can implement this: 1. Create a utils/ directory in your Nuxt project if it doesn't already exist. 2. Inside the utils/ directory, create a file for your reusable methods. For example, utils/myMethods.ts. 3. Define and export your methods in this file. Here's an example of how you might structure your reusable methods:
// utils/myMethods.ts

export function useSum(a: number, b: number) {
return a + b
}

export function formatDate(date: Date) {
// Your date formatting logic here
}

// Add more methods as needed
// utils/myMethods.ts

export function useSum(a: number, b: number) {
return a + b
}

export function formatDate(date: Date) {
// Your date formatting logic here
}

// Add more methods as needed
Once you've defined these methods in the utils/ directory, Nuxt will automatically make them available for use in any of your pages, components, or other files without the need for explicit imports. You can then use these methods in any of your pages or components like this:
<script setup>
const result = useSum(5, 3)
const formattedDate = formatDate(new Date())
</script>

<template>
<div>
<p>Sum: {{ result }}</p>
<p>Date: {{ formattedDate }}</p>
</div>
</template>
<script setup>
const result = useSum(5, 3)
const formattedDate = formatDate(new Date())
</script>

<template>
<div>
<p>Sum: {{ result }}</p>
<p>Date: {{ formattedDate }}</p>
</div>
</template>
This approach leverages Nuxt's auto-import feature, which scans the utils/ directory and makes its exports available globally in your application as described in the Nuxt documentation (https://nuxt.com/docs/guide/directory-structure/utils). By following this pattern, you ensure that your utility functions are: 1. Centralized in one location, making them easy to manage and update. 2. Automatically available throughout your application without manual imports. 3. Benefiting from tree-shaking, so only the methods you actually use are included in your final bundle. This is considered the best practice in Nuxt 3 for creating and using reusable methods across your application. ---------------------- Note: you can ask me a follow up question by @ mentioning me again :speech_balloon: ----------------------
Want results from more Discord servers?
Add your server